invoke Get Method by building method name from field name - Android java.lang.reflect

Android examples for java.lang.reflect:Method Invoke

Description

invoke Get Method by building method name from field name

Demo Code


import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;

public class Main{

    public static <T> T invokeGetMethod(Object o, String fieldName,
            Class<T> fieldType) throws IllegalArgumentException,
            SecurityException, IllegalAccessException,
            InvocationTargetException, NoSuchMethodException {
        String methodName = "get" + fieldName.substring(0, 1).toUpperCase()
                + fieldName.substring(1);
        return fieldType.cast(o.getClass().getMethod(methodName).invoke(o));
    }//from w  w  w. j a v a  2  s . c  om
}

Related Tutorials