get Value By Method via reflection - Android java.lang.reflect

Android examples for java.lang.reflect:Method Get

Description

get Value By Method via reflection

Demo Code


//package com.java2s;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Main {
    public static Object getValueByMethod(Object obj, String s) {
        Object ret = null;//from w w  w .  j a  v a  2s.  com
        String methodName = String.valueOf(s.charAt(0)).toUpperCase()
                + s.substring(1);

        try {
            Method m = obj.getClass().getMethod("get" + methodName);
            ret = m.invoke(obj);

        } catch (NoSuchMethodException e) {
            //            Log.w("method.invoke Failed. can't find the method", e);
            throw new RuntimeException(e);
        } catch (IllegalArgumentException e) {
            //            Log.w("method.invoke Failed. argument is illegal", e);
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            //            Log.w("method.invoke Failed. can't access the method", e);
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            //            Log.w("method.invoke Failed. can't invoke the target", e);
            throw new RuntimeException(e);
        }

        return ret;
    }
}

Related Tutorials