Retrieving the inherited attribute names/values using Java Reflection
no, you need to write it yourself. It is a simple recursive method called on Class.getSuperClass():
public static List<Field> getAllFields(List<Field> fields, Class<?> type) {
fields.addAll(Arrays.asList(type.getDeclaredFields()));
if (type.getSuperclass() != null) {
getAllFields(fields, type.getSuperclass());
}
return fields;
}
@Test
public void getLinkedListFields() {
System.out.println(getAllFields(new LinkedList<Field>(), LinkedList.class));
}
Get all Fields of class hierarchy
Try the following:
Field[] fields = c.getClass().getFields();
If you want all superclass fields, see the following:
Retrieving the inherited attribute names/values using Java Reflection
Get all fields (even private and inherited) from class
obj = obj.getClass().getSuperclass().cast(obj);
This line does not do what you expect it to do. Casting an Object
does not actually change it, it just tells the compiler to treat it as something else.
E.g. you can cast a List
to a Collection
, but it will still remain a List
.
However, looping up through the super classes to access fields works fine without casting:
Class<?> current = yourClass;
while(current.getSuperclass()!=null){ // we don't want to process Object.class
// do something with current's fields
current = current.getSuperclass();
}
BTW, if you have access to the Spring Framework, there is a handy method for looping through the fields of a class and all super classes:ReflectionUtils.doWithFields(baseClass, FieldCallback)
(also see this previous answer of mine: Access to private inherited fields via reflection in Java)
Access to private inherited fields via reflection in Java
In fact i use a complex type hierachy so you solution is not complete.
I need to make a recursive call to get all the private inherited fields.
Here is my solution
/**
* Return the set of fields declared at all level of class hierachy
*/
public static List<Field> getAllFields(Class<?> clazz) {
return getAllFieldsRec(clazz, new ArrayList<>());
}
private static List<Field> getAllFieldsRec(Class<?> clazz, List<Field> list) {
Class<?> superClazz = clazz.getSuperclass();
if (superClazz != null) {
getAllFieldsRec(superClazz, list);
}
list.addAll(Arrays.asList(clazz.getDeclaredFields()));
return list;
}
Java Reflection - Get Fields From Sub Class as well as Super Class
You will have to iterate over all the superclasses of your class, like this:
private List<Field> getInheritedPrivateFields(Class<?> type) {
List<Field> result = new ArrayList<Field>();
Class<?> i = type;
while (i != null && i != Object.class) {
Collections.addAll(result, i.getDeclaredFields());
i = i.getSuperclass();
}
return result;
}
How do I get all Record fields and its values via reflection in Java 17?
You can use the following method:
RecordComponent[] getRecordComponents()
You can retrieve name, type, generic type, annotations, and its accessor method from RecordComponent
.
Point.java:
record Point(int x, int y) { }
RecordDemo.java:
import java.lang.reflect.RecordComponent;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
public class RecordDemo {
public static void main(String args[]) throws InvocationTargetException, IllegalAccessException {
Point point = new Point(10,20);
RecordComponent[] rc = Point.class.getRecordComponents();
System.out.println(rc[0].getAccessor().invoke(point));
}
}
Output:
10
Alternatively,
import java.lang.reflect.RecordComponent;
import java.lang.reflect.Field;
public class RecordDemo {
public static void main(String args[])
throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException {
Point point = new Point(10, 20);
RecordComponent[] rc = Point.class.getRecordComponents();
Field field = Point.class.getDeclaredField(rc[0].getAccessor().getName());
field.setAccessible(true);
System.out.println(field.get(point));
}
}
How to get Java reflect to spot fields in the super class? not just the actual class
You can use this.getClass().getSuperClass()
until this getSuperClass()
method returns null to get the parent fields.
So, the best would be that you factorize your code. Implement one method that takes a list of Field
as parameter and do your logical part within it, and a main method that search for fields through a while(superClass != null)
loop.
Why reflection does not provide method to query all fields in inheritance hierarchy?
This is because a child class
is not aware of any private
fields in a parent class
- it does not inherit them.
The problem at hand can be solved very easily by walking up the class hierarchy with getSuperClass
public static Field getField(final Class<?> toReflectOn, final String fieldName) throws NoSuchFieldException {
try {
return toReflectOn.getField(fieldName);
} catch (NoSuchFieldException ex) {
if (toReflectOn.getSuperclass() != null) {
return getField(toReflectOn.getSuperclass(), fieldName);
}
throw ex;
}
}
This other SO post provides a more sophisticated approach that loops over all fields in the class hierarchy.
Related Topics
Jsf Convertdatetime Renders the Previous Day
Differencebetween 'Java', 'Javaw', and 'Javaws'
How to Add a Maven Dependency in Eclipse
How to Reference Another Property in Java.Util.Properties
Tokenizing a String But Ignoring Delimiters Within Quotes
Spring Boot @Responsebody Doesn't Serialize Entity Id
Is Httpsession Thread Safe, Are Set/Get Attribute Thread Safe Operations
Compile-Time Constants and Variables
How to Get the Caller Class in Java
Write a File in Hdfs with Java
Best Way to Format Multiple 'Or' Conditions in an If Statement
How Can a Class Have a Member of Its Own Type, Isn't This Infinite Recursion
Embed a Jre in a Windows Executable
Varargs and the '...' Argument