mardi 31 décembre 2019

Find field is of which class, parent or child in Java?

Can somebody help on this?

I have class. This is just demo, in actual I have more fields.

public class ParentData
{
   private String field2 = "";
}

public class Data extends ParentData
{
   private String field1 = "";
}
Field[] allFields = getAllFieldsofParentAndChildClass();

// allFields contains all fields of parent and child class.

for(Field field : allFields)
{
   String className = field.getDeclaringClass().getSimpleName();  //Line 5
   String fieldName = field.getName();

   String parentClass = field.getDeclaringClass().getSuperClass().getSimpleName();  //Line 8
}

On line 5, i want the name of actual class. For e.g. if field belongs to parent class then parent class name and if child class then child class name

On line 8, I'm getting the parent class but with every field. I want parent class name only with parent class fields.

How can I achieve that?





Aucun commentaire:

Enregistrer un commentaire