集册 Java实例教程 使用反射从构造器访问修饰符

使用反射从构造器访问修饰符

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

549
使用反射从构造器访问修饰符

import java.lang.reflect.Constructor;

import java.lang.reflect.Modifier;

import java.lang.reflect.Type;

import static java.lang.System.out;/* 来 自 时代Java公众号 - N o w J a  v a . c o m*/


public class ConstructorAccess {

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

        try {

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

            Constructor[] allConstructors = c.getDeclaredConstructors();

            for (Constructor ctor : allConstructors) {

                int searchMod = modifierFromString(args[1]);

                int mods = accessModifiers(ctor.getModifiers());

                if (searchMod == mods) {

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

                    out.format("  [ synthetic=%-5b var_args=%-5b ]%n",

                            ctor.isSynthetic(), ctor.isVarArgs());/*来自 N o w  J a v a  . c o m*/

                }

            }


            // production code should handle this exception more gracefully

        } catch (ClassNotFoundException x) {

            x.printStackTrace();

        }

    }


    private static int accessModifiers(int m) {

        return m

                & (Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED);

    }


    private static int modifierFromString(String s) {

        if ("public".equals(s))

            return Modifier.PUBLIC;

        else if ("protected".equals(s))

            return Modifier.PROTECTED;

        else if ("private".equals(s))

            return Modifier.PRIVATE;

        else if ("package-private".equals(s))

            return 0;

        else

            return -1;

    }

}


展开阅读全文