Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using reflection to find class member value

Im using reflection to find class member and their related type with the following code, but my question is if there is a way to find class default value ?
For example in this case i need the value 1L.

public class SalesOrrP implements Serializable {
    private static final long serialUID = 1L;
}

I have used the following code to find member name and type

Field[] declaredFields = clsObj.getClass().getDeclaredFields();
for (Field field : declaredFields) {
    // Get member name & types
    Class<?> fieldType = field.getType();
    Type genericType = field.getGenericType();
    String fieldTypeName = fieldType.getName();
    String memberName = field.getName();
    if (genericType instanceof ParameterizedType) {
        ParameterizedType pt = (ParameterizedType) genericType;
        for (Type typeOfReferance : pt.getActualTypeArguments()) {
            //...
        }
    }
}
like image 543
Jean Tennie Avatar asked Mar 31 '26 05:03

Jean Tennie


2 Answers

If all you need is to access the value of the field, you simply need to make it accessible and get the value:

field.setAccessible(true);
long value = field.getLong(null);
like image 192
assylias Avatar answered Apr 02 '26 18:04

assylias


For static fields, you don't need to create a new instance. In your case, SalesOrrP.class.getDeclaredField("serialUID").get(null) should be enough.

For non static fields, you can't get the initialization value you're talking about, since it is automatically relocated by the compiler within the constructor of the class. It means that you have to create a new instance of the class to get the value you're looking for.

If you're sure the classes provide a nullary constructor (i.e. a constructor with no argument), here is what you could do:

public static <T> Map<String, Object> getDefaultValues(Class<T> clazz, T instance) throws Exception {
    Map<String, Object> defaultValues = new HashMap<String, Object>();
    if (instance == null) {
        instance = clazz.newInstance();
    }
    for (Field field : clazz.getDeclaredFields()) {
        field.setAccessible(true);
        Object defaultValue = field.get(instance);
        defaultValues.put(field.getName(), defaultValue);
    }
    return defaultValues;
}

For example, in your case, getDefaultValues(SalesOrrP.class, null) will return {serialUID=1}. If you already have an instance of your class, give it as a 2nd argument (instead of null in the above example).

like image 37
sp00m Avatar answered Apr 02 '26 19:04

sp00m