Using reflection to determine the value of a class member

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

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

      

I used the following code to find the 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()) {
            //...
        }
    }
}

      

+3


source to share


3 answers


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

should suffice.

For non-static fields, you cannot get the initialization value you are talking about as it is automatically moved by the compiler inside the class constructor. This means that you need to create a new instance of the class to get the value you are looking for.

If you are sure that classes provide a nullable constructor (i.e. a constructor with no argument), here's 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, specify it as the 2nd argument (instead of null

in the above example).

+2


source


If you only need to access the value of a field, you just need to make it available and get the value:



field.setAccessible(true);
long value = field.getLong(null);

      

+3


source


This final value can only be changed with reflection. If you know that reflection cannot be used, you are safe.

If not, you can create a new instance and get the new instance value.

-1


source







All Articles