Java反射(reflect)

2017-05-24  本文已影响7人  Cloverss
    private static void getMethodInfo(Object o) {
        Class clzz = o.getClass();
        System.out.println("类名称是:" + clzz.getSimpleName());
        Method[] methods = clzz.getDeclaredMethods();       //自己的方法
        Method[] allMethod = clzz.getMethods();            // 所有public 方法 包括父类
        for (int i = 0; i < allMethod.length; i++) {
            System.out.print("方法是:");
            Method method = allMethod[i];
            System.out.print(method.getModifiers()+" ");
            Class<?> type = method.getReturnType();
            System.out.print(type.getSimpleName() + " ");
            System.out.print(method.getName() + "(");
            Class<?>[] parameterTypes = method.getParameterTypes();
            for (int j = 0; j < parameterTypes.length; j++) {
                System.out.print(parameterTypes[j].getSimpleName() + " ");
            }
            System.out.println(")");
        }
        System.out.println();
    }


    private static void getFieldInfo(Object object) {
        Class clzz = object.getClass();
        Field[] fields = clzz.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            Class<?> type = fields[i].getType();// 返回的是成员变量的类型的 类类型,比如 String name; 返回的是String的类类型,即String.class
            System.out.print(type.getSimpleName() + " ");
            System.out.println(fields[i].getName() + ";");
        }
    }



    private static void getConstructorInfo(Object object) {
        Class clzz = object.getClass();
//        Constructor[] constructors = clzz.getConstructors(); //所有的公有构造方法
        Constructor[] constructors = clzz.getDeclaredConstructors();    //自己自己声明的构造方法
        for (int i = 0; i < constructors.length; i++) {
            System.out.print(constructors[i].getName() + "(");
            Class[] parameterTypes = constructors[i].getParameterTypes();
            for (int j = 0; j < parameterTypes.length; j++) {   //参数列表的类类型
                System.out.print(parameterTypes[j].getSimpleName() + ",");
            }
            System.out.print(")");
            System.out.println();
        }
    }
上一篇 下一篇

猜你喜欢

热点阅读