集册 Java实例教程 获取可访问方法

获取可访问方法

欢马劈雪     最近更新时间:2020-01-02 10:19:05

357
获取可访问方法
//来 自 时 代 J a v a 公 众 号

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);

                }

            }

        }

        return method;/* 来自 时代Java公众号*/

    }

    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 
展开阅读全文