Define the fields of a class using dynamic data.(META PROGRAMMING)

F

Fo

Dear all,
I am trying to parse a textual file into classes.
For each line (or 2-3 consecutive lines), there is the definition of
an object.
The objects are fixed and the structure of the line is also
predetermined (space-separated file).
I am not using a regular-expression parser or a scanner (like JFlex)
because the syntax is pretty easy.
An example of line is:
"OBJ1 FIELD1 FIELD2 FIELD3 FIELD4 FIELD5"
Up to now I explicitly created the classes defining the object and I
parsed the content using String.substring(i,j), for each line.
It works well but I was wondering if it was possible to:

1. Define the class JIT, I mean given a description of classes with
the name of the class, the description of the fields and the indexes
of the fields, generate automatically the class.It is a kind of
metaprogramming, I suppose.

2.Invoke a method or a field of a class defined by a String

[...]
Object obj ;// defined somewehere else
String nameField="field1";
obj.nameField="AAA"; //this should read obj.field1="AAA"
[...]
I suppose that it is possible to do it using java.lang.Class.getFields
() and then using Fields.set(...) checking if the name of the field is
the one I want to change.
Is it the correct way?


Thank you
Fo
 
M

Martin Gregorie

An example of line is:
"OBJ1 FIELD1 FIELD2 FIELD3 FIELD4 FIELD5" Up to now I explicitly created
the classes defining the object and I parsed the content using
String.substring(i,j), for each line. It works well but I was wondering
if it was possible to:
I'd use String.split() rather that mess round with substring and its
subscript trappings.
2.Invoke a method or a field of a class defined by a String

[...]
Object obj ;// defined somewehere else String nameField="field1";
obj.nameField="AAA"; //this should read obj.field1="AAA" [...]
Better to define the class using a constructor with a single String[]
parameter and put the class-specific field naming and conversions in the
constructor. If any of the conversions can throw Exceptions I'd move them
to a separate method, e.g. void parse(String[] args)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,074
Latest member
StanleyFra

Latest Threads

Top