集册 Java实例教程 访问修饰符从使用反射的方法获取

访问修饰符从使用反射的方法获取

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

589
访问修饰符从使用反射的方法获取
//来 自 时 代      J a v a   公   众 号 - nowjava.com

import java.lang.reflect.Method;

import java.lang.reflect.Modifier;

import static java.lang.System.out;


public class MethodModifierSpy {


    private static int count;


    private static synchronized void inc() {

        count++;

    }


    private static synchronized int cnt() {

        return count;

    }


    public static void main(String... args) {

        try {
        /** from 
        NowJava.com**/

            Class<?> c = Class.forName(args[0]);

            Method[] allMethods = c.getDeclaredMethods();

            for (Method m : allMethods) {

                if (!m.getName().equals(args[1])) {

                    continue;

                }

                out.format("%s%n", m.toGenericString());

                out.format("  Modifiers:  %s%n",

                        Modifier.toString(m.getModifiers()));

                out.format(

                        "  [ synthetic=%-5b var_args=%-5b bridge=%-5b ]%n",

                        m.isSynthetic(), m.isVarArgs(), m.isBridge());

                inc();

            }

            out.format("%d matching overload%s found%n", cnt(),

                    (cnt() == 1 ? "" : "s"));


            // production code should handle this exception more gracefully

        } catch (ClassNotFoundException x) {

            x.printStackTrace();

        }

    }

}


展开阅读全文