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)?
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.
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.
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.
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.
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.
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With