Can I add new fields to a class using reflection

Is it possible to add a new field to a class if I have an object of a class class and how can I determine if a particular class is referenced or used in this class literal?

+6
source share
2 answers

You cannot directly add a new field to a Class object. There are third-party APIs that you can use to create or modify classes (for example, ASM, BCEL), although they are best avoided because they add more 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 superclass. // you'll have to do a recursive lookup if you want super fields too. for(Field field : A.class.getDeclaredFields()) { if(B.class.equals(field.getType()) { System.out.println("A." + field.getName() + " is of type B"); } } 
+5
source

You have not indicated what you need this function for, but you might consider JAXB if you want to stick with Java: you declare your Java class as XML and generate it dynamically. Perhaps this helps.

+1
source

Source: https://habr.com/ru/post/897386/


All Articles