Can I add new fields in a Class using reflection

2019-06-16 10:01发布

问题:

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 ?

回答1:

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


回答2:

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.