反射相关方法

       Class clazz = Class.forName("com.test.zzz.Person");

        //获取clazz对应类中的所有方法,不能获取private方法,且获取从父类继承来的所有方法
        Method[] methods = clazz.getMethods();
        for(Method method:methods){
            System.out.print(" "+method.getName()+"()");
        }
       
        System.out.println("---------------------------");

        //获取所有方法,包括私有方法,所有声明的方法,都可以获取到,且只获取当前类的方法
        methods = clazz.getDeclaredMethods();
        for(Method method:methods){
            System.out.print(" "+method.getName()+"()");
        }
 

        //获取指定的方法需要参数名称和参数列表,无参则不需要写方法
        Method method = clazz.getDeclaredMethod("setName", String.class);
        System.out.println(method);

       注意:方法 public void setAge(int age) {  }
        这样写是获取不到的,如果方法的参数类型是int型
        如果方法用于反射,那么要么int类型写成Integer: public void setAge(Integer age) {  }
        要么获取方法的参数写成int.class

        method = clazz.getDeclaredMethod("setAge", int.class);
        System.out.println(method);


        //执行方法,第一个参数表示执行哪个对象的方法剩下的参数是执行方法时需要传入的参数
        Object obje = clazz.newInstance();
        method.invoke(obje,18);

        //私有方法的执行,必须在调用invoke之前加上一句method.setAccessible(true);
        method = clazz.getDeclaredMethod("privateMethod");
        System.out.println(method);
        System.out.println("---------------------------");
        System.out.println("执行私有方法");
        method.setAccessible(true);
        method.invoke(obje);

猜你喜欢

转载自blog.csdn.net/u010207898/article/details/131964905