Since I do not have the AnotherClassOne and AnotherClassTwo , I put Integer and Boolean instead:
public class SomeClass { private String string; private Boolean classOne; private Integer classTwo; private int i; }
The SomeClass class SomeClass in my default package, so the Class object is easier for him to get by the name:
Class c = Class.forName("SomeClass");
also the Class object can be obtained from the instance: obj.getClass() .
Further, it suffices to use the methods of the Class and Field classes. Just in case, I note that the Field class will have to be imported ( import java.lang.reflect.Field; ).
Field[] fs = c.getDeclaredFields(); // ΠΏΠΎΠ»ΡΡΠΈΠ»ΠΈ ΠΌΠ°ΡΡΠΈΠ² Ρ ΠΎΠ±ΡΠ΅ΠΊΡΠ°ΠΌΠΈ Field, ΡΠΎΠΎΡΠ²Π΅ΡΡΡΠ²ΡΡΡΠΈΠ΅ ΠΏΠΎΠ»ΡΠΌ ΠΊΠ»Π°ΡΡΠ° SomeClass for(int i = 0; i < fs.length; i++) System.out.println(fs[i].getName()); // ΠΈΠΌΡ ΠΏΠΎΠ»Ρ for(int i = 0; i < fs.length; i++) System.out.println(fs[i].getType()); // ΠΊΠ»Π°ΡΡ ΠΏΠΎΠ»Ρ for(int i = 0; i < fs.length; i++) System.out.println(fs[i].getType().isPrimitive()); // ΠΏΡΠΈΠΌΠΈΡΠΈΠ²Π½ΠΎΠ΅ ΠΏΠΎΠ»Π΅ ΠΈΠ»ΠΈ Π½Π΅Ρ?
For the SomeClass example SomeClass output is as follows:
Field names
string
classOne
classTwo
i
Types
class java.lang.String
class java.lang.Boolean
class java.lang.Integer
int
Is the type primitive?
false
false
false
true
Just in case, I note that the result of calling field.getType() is an instance of class Class , and not its string representation, which is output by the println() function. This allows the result of the call to apply a check on the primitive type of the method field.getType().isPrimitive() .
Accordingly, if the field is not primitive, then just get its Class object using getType() method. Then, for this Class object, the procedure described earlier can get its fields, field types, and for non-primitive types, repeat the whole procedure again. In one of the comments this recursive algorithm has already been described.