get Accessible Method - Java Reflection

Java examples for Reflection:Method

Description

get Accessible Method

Demo Code


import java.lang.reflect.Method;

public class Main{
    private static Method getAccessibleMethod(Method method, Class<?> clazz)
            throws NoSuchMethodException, SecurityException {
        if (method == null)
            return null;
        if (!method.isAccessible()) {
            try {
                method.setAccessible(true);
            } catch (SecurityException e) {
                String methodName = method.getName();
                try {
                    method = searchPublicMethod(clazz, methodName);
                } catch (NoSuchMethodException e1) {
                    method = searchPublicMethod(clazz.getInterfaces(),
                            methodName);
                }/*  w ww.  ja va  2s . co  m*/
            }
        }
        return method;
    }
    private static Method searchPublicMethod(Class<?>[] classes,
            String methodName) throws NoSuchMethodException,
            SecurityException {
        if (classes != null && classes.length > 0) {
            for (int i = 0, n = classes.length; i < n; i++) {
                Class<?> cls = classes[i];
                try {
                    return searchPublicMethod(cls, methodName);
                } catch (NoSuchMethodException e) {
                    // ignore, continue
                }
            }
        }
        throw new NoSuchMethodException(); // ?????
    }
    private static Method searchPublicMethod(Class<?> cls, String methodName)
            throws NoSuchMethodException, SecurityException {
        Method method = cls.getMethod(methodName, new Class[0]);
        if (ClassUtils.isPublicMethod(method)
                && (method.getParameterTypes() == null || method
                        .getParameterTypes().length == 0)) { // ????????????
            return method;
        }
        throw new NoSuchMethodException(); // ?????
    }
}

Related Tutorials