Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting first parent's fields via reflection

I'm trying to get the fields and values of my object's first parent. My current code is this:

Class<? extends Object> cls = obj.getClass();
Field[] fields = cls.getDeclaredFields();
for ( Field field : fields )
{
    String fieldName = field.getName();
    String fieldValue = field.get(obj);
}

My class structure is similar to this:

class A
{
    int x;
}

class B extends A
{
    int y;
}

class C extends B
{
    int z;
}

Now, I pass a C object to the method and I want to get all fields from C and B, but not from A. Is there a way to do this (using reflection, I don't want to implement other methods)?

like image 454
Luchian Grigore Avatar asked Nov 01 '11 12:11

Luchian Grigore


People also ask

How do you inherit fields using Reflection?

The only way we have to get only inherited fields is to use the getDeclaredFields() method, as we just did, and filter its results using the Field::getModifiers method. This one returns an int representing the modifiers of the current field. Each possible modifier is assigned a power of two between 2^0 and 2^7.

How do I get fields from parent class?

Now how can i get fields of parent class in this case 'a'. You can use getField() with public fields. Otherwise, you need to loop through parent classes yourself.

What is reflection in unit testing?

Introduction. ReflectionTestUtils is a part of Spring Test Context framework. It is a collection for reflection-based utility methods used in a unit, and integration testing scenarios to set the non-public fields, invoke non-public methods, and inject dependencies.


2 Answers

Luchian, use the getSuperclass() method to obtain a reference to a Class object that represents a superclass type of the object in question. After that it is going to be easy for you to get fields the same way you do in your example.

like image 183
DejanLekic Avatar answered Oct 04 '22 00:10

DejanLekic


Create a method

public static void printFieldsFor(Class cls, Object obj) {
  Field[] fields = cls.getDeclaredFields();
  for ( Field field : fields ) {
    String fieldName = field.getName();
    String fieldValue = field.get(obj);
  }
}

printFieldsFor(object.getClass(), obj);
printFieldsFor(object.getClass().getSuperclass(), obj);

or use a loop

for(Class cls = object.getClass(); 
    cls!=null && cls!=A.class; 
    cls = cls.getSuperclass()) {
  for(Field field : cls.getDeclaredFields()) {
     String fieldName = field.getName();
     String fieldValue = field.get(obj);
     // do something with the field.
  }
}
like image 40
Peter Lawrey Avatar answered Oct 04 '22 00:10

Peter Lawrey