get Object's Method - Android java.lang.reflect

Android examples for java.lang.reflect:Method Get

Description

get Object's Method

Demo Code


//package com.java2s;
import java.lang.reflect.*;

public class Main {
    public static Method getObjectMethod(Object object, String methodName,
            Class<?>... paramsTypes) throws NoSuchMethodException {
        Method m = getClassMethod(object.getClass(), methodName,
                paramsTypes);/*from  w  w  w .  j a  v  a  2 s . c  o  m*/
        makeAccessible(m);
        return m;
    }

    public static Method getClassMethod(Class clazz, String methodName,
            Class<?>... fieldParams) throws NoSuchMethodException {
        try {
            return clazz.getDeclaredMethod(methodName, fieldParams);
        } catch (NoSuchMethodException e) {
            Class superClass = clazz.getSuperclass();
            if (superClass == null) {
                throw e;
            } else {
                return getClassMethod(superClass, methodName, fieldParams);
            }
        }
    }

    private static void makeAccessible(Method method) {
        if (!Modifier.isPublic(method.getModifiers())
                || !Modifier.isPublic(method.getDeclaringClass()
                        .getModifiers())) {
            method.setAccessible(true);
        }
    }

    private static void makeAccessible(Field field) {
        if (!Modifier.isPublic(field.getModifiers())
                || !Modifier.isPublic(field.getDeclaringClass()
                        .getModifiers())) {
            field.setAccessible(true);
        }
    }
}

Related Tutorials