Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I add new fields in a Class using reflection

Can I add a new field to a class if I have its class literal object and how can I determine that a particular Class is referenced or used in that class literal ?

like image 273
Chandan Avatar asked Sep 15 '11 13:09

Chandan


2 Answers

You can't directly add a new field to the Class object. There are third-party APIs that you can use to do class generation or modification (e.g. ASM, BCEL), though they're best avoided because they add a lot of complexity.

As for the second part of your question, you can use the Class object to go through the fields and examine them.

// NOTE : this only looks at the fields in A and not it's superclass.
//        you'll have to do a recursive lookup if you want super's fields too.
for(Field field : A.class.getDeclaredFields()) {
    if(B.class.equals(field.getType()) {
        System.out.println("A." + field.getName() + " is of type B");
    }
}
like image 86
stevevls Avatar answered Sep 20 '22 02:09

stevevls


You don't state what you need this feature for, but maybe you'd like to consider JAXB if you want to stick to Java: you declare your Java class as XML and it is generated dynamically. Maybe that helps.

like image 22
Andreas Tasoulas Avatar answered Sep 19 '22 02:09

Andreas Tasoulas