Chandan
Chandan

Reputation: 229

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 ?

Upvotes: 12

Views: 16254

Answers (2)

Andreas Tasoulas
Andreas Tasoulas

Reputation: 453

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.

Upvotes: 2

stevevls
stevevls

Reputation: 10853

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");
    }
}

Upvotes: 6

Related Questions