lundi 19 octobre 2015

How can I get the instance of an object that is determined in the class

I have a class that has structure containing other classes, each of these classes also may contain different classes. So this is tree structure of classes.

public class FirstLevelClass {
   public SecondLevelClass1 secondLevelClass1;
   public SecondLevelClass2 secondLevelClass2;
   ...
}

public class SecondLevelClass1 {
   public ThirdLevelClass thirdLevelClass;
   public String fieldSecondLevelClass;
   ...
}

I have initialized variable of FirstLevelClass.

FirstLevelClass firstLevelClass;

I need to get instance of secondLevelClass1 that is stored inside firstLevelClass. How can I do that having a name of the class SecondLevelClass1?

Basically I need to get value of the field inside SecondLevelClass1. But I failed when wrote this:

String fieldName = "fieldSecondLevelClass";
Field[] fields = firstLevelClass.getClass().getDeclaredFields();
Object foundValue = null;

for (Field field : fields) {
   Field foundField = null;
   foundField = field.getType().getDeclaredField(fieldName);
   foundValue = fieldSecondLevelClass.get((Class.forName(foundField.getDeclaringClass().getName())).newInstance());
}

Because the instance that I call fieldSecondLevelClass.get(...) with isnt initialized. But if i write

foundValue = foundField.get(((FirstLevelClass) firstLevelClass).secondLevelClass1);

it will work fine. So, do any of you ideas how can I pass right instance of secondLevelClass1 using the name of it and instance of FirstLevelClass to fieldSecondLevelClass.get(...)?





Aucun commentaire:

Enregistrer un commentaire