I have a class that contains other classes as fields:

public class SomeClass { private String string; private AnotherClassOne classOne; private AnotherClassTwo classTwo; private int i; } 

And here I need to get help Reflection of all its fields and the fields of its fields, if it is a different class.

  • Get the field, get the value, start the procedure from the beginning for the value of the field - etki
  • it returns the Class type and gives the left margins, and it swears - Fairkhan

2 answers 2

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.

    Try the Commons BeanUtils library

     String propValue = BeanUtil.getProperty(someClassObj, "classOne.someProp");