JAVA反射详解

反射的概述:

是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;

对于任意一个对象,都能够调用它的任意属性和方法;

这种动态获取信息以及动态调用对象方法的功能称为Java语言的反射机制。

获取Class类对象的三种方式:

1:类名+点+class属性

2:对象名.getClass()方法

3:Class.forName(全类名)方法

实例代码 :

public class Student {
    private String name;
    private int age;

    public Student() {
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void study(){
        System.out.println("学生在学习");
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
public class ReflectDemo1 {
    public static void main(String[] args) throws ClassNotFoundException {
        //1.Class类中的静态方法forName("全类名")
        //全类名:包名 + 类名
        Class clazz = Class.forName("com.itbo.fanshe.Student");
        System.out.println(clazz);

        //通过Class属性来获取.
        Class clazz2 = Student.class;
        System.out.println(clazz2);

        //3.利用对象的getClass方法来获取class对象
        //getClass方法是定义在Object类中.
        Student student = new Student();
        Class clazz3 = student.getClass();
        System.out.println(clazz3);

        System.out.println(clazz == clazz2);
        System.out.println(clazz3 == clazz2);
    }
}

反射获取构造方法并使用:

Class类获取构造方法对象的方法:

 示例代码
public class StudentTest02 {

    private String name;
    private int age;

    //私有的有参构造方法
    private StudentTest02(String name) {
        System.out.println("name的值为:" + name);
        System.out.println("private...Student...有参构造方法");
    }

    //公共的无参构造方法
    public StudentTest02() {
        System.out.println("public...Student...无参构造方法");
    }

    //公共的有参构造方法
    public StudentTest02(String name, int age) {
        System.out.println("name的值为:" + name + "age的值为:" + age);
        System.out.println("public...Student...有参构造方法");
    }
}

public class ReflectDemo2 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException {
//        method1();
//        method2();
//        method3();
        method4();
    }

    private static void method1() throws ClassNotFoundException, NoSuchMethodException {
         //Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes):
        //返回单个构造方法对象
        //1.获取Class对象
        Class clazz = Class.forName("com.itbo.fanshe.StudentTest02");
        Constructor constructor = clazz.getDeclaredConstructor(String.class);
        System.out.println(constructor);
    }

    private static void method2() throws ClassNotFoundException, NoSuchMethodException {
        //Constructor<T> getConstructor(Class<?>... parameterTypes):
        //返回单个公共构造方法对象
        //1.获取Class对象
        Class clazz = Class.forName("com.itbo.fanshe.StudentTest02");
        //小括号中,一定要跟构造方法的形参保持一致.
        Constructor constructor = clazz.getConstructor();
        System.out.println(constructor);

        Constructor constructor1 = clazz.getConstructor(String.class, int.class);
        System.out.println(constructor1);
    }

    private static void method3() throws ClassNotFoundException, NoSuchMethodException {
        //Constructor<?>[] getDeclaredConstructors():
        //返回所有构造方法对象的数组
        //1.获取Class对象
        Class clazz = Class.forName("com.itbo.fanshe.StudentTest02");
        Constructor[] constructors = clazz.getDeclaredConstructors();
        for (Constructor constructor : constructors) {
            System.out.println(constructor);
        }
    }

    private static void method4() throws ClassNotFoundException, NoSuchMethodException {
        //Constructor<?>[] getConstructors():
        //返回所有公共构造方法对象的数组
        //1.获取Class对象
        Class clazz = Class.forName("com.itbo.fanshe.StudentTest02");
        Constructor[] constructors = clazz.getConstructors();
        for (Constructor constructor : constructors) {
            System.out.println(constructor);
        }
    }
}

public class ReflectDemo3 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        //T newInstance(Object... initargs):根据指定的构造方法创建对象
//        method1();
//        method2();
//        method3();
        method4();

    }

    private static void method4() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        //获取一个私有的构造方法并创建对象
        //1.获取class对象
        Class clazz = Class.forName("com.itbo.fanshe.StudentTest02");

        //2.获取一个私有化的构造方法.
        Constructor declaredConstructor = clazz
         .getDeclaredConstructor(String.class);
        //被private修饰的成员,不能直接使用的
        //如果用反射强行获取并使用,需要临时取消访问检查
        declaredConstructor.setAccessible(true);
        
        //直接创建对象.
        StudentTest02 instance = (StudentTest02) declaredConstructor
         .newInstance("张三");
        System.out.println(instance);
    }

    private static void method3() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        //1.获取class对象
        Class clazz = Class.forName("com.itbo.fanshe.StudentTest02");
        StudentTest02 instance = (StudentTest02) clazz.newInstance();
        System.out.println(instance);
    }

    private static void method2() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        //1.获取class对象
        Class clazz = Class.forName("com.itbo.fanshe.StudentTest02");

        //2.获取构造方法对象
        Constructor constructor = clazz.getConstructor();

        //3.利用空参来创建Student的对象
        StudentTest02 instance = (StudentTest02) constructor.newInstance();
        System.out.println(instance);
    }

    private static void method1() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {

        //1.获取class对象
        Class clazz = Class.forName("com.itbo.fanshe.StudentTest02");
        //2.获取构造方法对象
        Constructor constructor = clazz.getConstructor(String.class, int.class);
        //3.利用newInstance创建Student的对象
        StudentTest02 instance = (StudentTest02) constructor
        .newInstance("zhangsan", 18);
        System.out.println(instance);
    }
}

小结

1:获取class对象

三种方式: Class.forName(“全类名”), 类名.class, 对象名.getClass()

2:获取里面的构造方法对象

getConstructor (Class<?>... parameterTypes)getDeclaredConstructor (Class<?>... parameterTypes)

3:如果是public的,直接创建对象

newInstance(Object... initargs)

4:如果是非public的,需要临时取消检查,然后再创建对象

setAccessible(boolean) 暴力反射

反射获取成员变量并使用

public class StudentFiled {
    public String name;

    public int age;

    public String gender;

    private int money = 300;

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", gender='" + gender + '\'' +
                ", money=" + money +
                '}';
    }
}

 

public class ReflectDemo4 {
    
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
//         method1();
//        method2();
//        method3();
        method4();

    }

    private static void method4() throws ClassNotFoundException, NoSuchFieldException {
        //        Field getDeclaredField(String name):返回单个成员变量对象
        //1.获取class对象
        Class clazz = Class.forName("com.itbo.fanshe.StudentFiled");

        //2.获取money成员变量
        Field field = clazz.getDeclaredField("money");

        //3.打印一下
        System.out.println(field);
    }

    private static void method3() throws ClassNotFoundException, NoSuchFieldException {

        //Field getField(String name):返回单个公共成员变量对象
        //想要获取的成员变量必须是真实存在的
        //且必须是public修饰的.
        //1.获取class对象
        Class clazz = Class.forName("com.itbo.fanshe.StudentFiled");

        //2.获取name这个成员变量
        Field field = clazz.getField("name");
//        Field field = clazz.getField("name1");
//        Field field = clazz.getField("money");

        //3.打印一下
        System.out.println(field);
    }

    private static void method2() throws ClassNotFoundException {
        //Field[] getDeclaredFields():返回所有成员变量对象的数组
        //1.获取class对象
        Class clazz = Class.forName("com.itbo.fanshe.StudentFiled");

        //2.获取所有的Field对象
        Field[] fields = clazz.getDeclaredFields();

        //3.遍历
        for (Field field : fields) {
            System.out.println(field);
        }
    }
    

    private static void method1() throws ClassNotFoundException {
        //Field[] getFields():返回所有公共成员变量对象的数组

        //1.获取class对象
        Class clazz = Class.forName("com.itbo.fanshe.StudentFiled");

        //2.获取Field对象.
        Field[] fields = clazz.getFields();

        //3.遍历
        for (Field field : fields) {
            System.out.println(field);
        }
    }
}

Field类用于给成员变量赋值的方法

public class ReflectDemo5 {

    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, InstantiationException {
//        Object get(Object obj) 返回由该 Field表示的字段在指定对象上的值。
//        method1();
        method2();

    }

    private static void method2() throws ClassNotFoundException, NoSuchFieldException, InstantiationException, IllegalAccessException {
        //1.获取class对象
        Class clazz = Class.forName("com.itbo.fanshe.StudentFiled");

        //2.获取成员变量Field的对象
        Field money = clazz.getDeclaredField("money");

        //3.取消一下访问检查
        money.setAccessible(true);

        //4.调用get方法来获取值
        //4.1创建一个对象
        StudentFiled instance = (StudentFiled) clazz.newInstance();

        //4.2获取指定对象的money的值
        Object o = money.get(instance);

        System.out.println(o);
    }

    private static void method1() throws ClassNotFoundException, NoSuchFieldException, InstantiationException, IllegalAccessException {
        //void set(Object obj, Object value):给obj对象的成员变量赋值为value
        //1.获取class对象
        Class clazz = Class.forName("com.itbo.fanshe.StudentFiled");

        //2.获取name这个Field对象
        Field name = clazz.getField("name");
        
        //3.利用set方法进行赋值.
        //3.1先创建一个Student对象
        StudentFiled instance = (StudentFiled) clazz.newInstance();

        //3.2有了对象才可以给指定对象进行赋值
        name.set(instance,"zhangsan");

        System.out.println(instance);
    }
}

反射获取成员方法并使用

 

public class ReflectDemo6 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException {
//        method1();
//        method2();
//        method3();
//        method4();
        method5();
    }

    private static void method5() throws NoSuchMethodException, ClassNotFoundException {
        //Method getDeclaredMethod(String name, Class<?>... parameterTypes):
        //返回单个成员方法对象
        //1.获取class对象
        Class clazz = Class.forName("com.itbo.fanshe.StudentCon");
        //2.获取一个成员方法show
        Method method = clazz.getDeclaredMethod("show");
        //3.打印一下
        System.out.println(method);
    }

    private static void method4() throws ClassNotFoundException, NoSuchMethodException {
        //1.获取class对象
        Class clazz = Class.forName("com.itbo.fanshe.StudentCon");
        //2.获取一个有形参的方法function2
        Method method = clazz.getMethod("function2", String.class);
        //3.打印一下
        System.out.println(method);
    }

    private static void method3() throws ClassNotFoundException, NoSuchMethodException {
        // Method getMethod(String name, Class<?>... parameterTypes) :
        //返回单个公共成员方法对象
        //1.获取class对象
        Class clazz = Class.forName("com.itbo.fanshe.StudentCon");
        //2.获取成员方法function1
        Method function1 = clazz.getMethod("function1");
        System.out.println(function1);
    }

    private static void method2() throws ClassNotFoundException {
        //Method[] getDeclaredMethods():
        //返回所有成员方法对象的数组,不包括继承的
        //1.获取class对象
        Class clazz = Class.forName("com.itbo.fanshe.StudentCon");
        //2.获取Method对象
        Method[] methods = clazz.getDeclaredMethods();
        for (Method method : methods) {
            System.out.println(method);
        }
    }

    private static void method1() throws ClassNotFoundException {
        //Method[] getMethods():返回所有公共成员方法对象的数组,包括继承的
        //1.获取class对象
        Class clazz = Class.forName("com.itbo.fanshe.StudentCon");
        //2.获取成员方法对象
        Method[] methods = clazz.getMethods();
        for (Method method : methods) {
            System.out.println(method);
        }
    }
}

Method类用于执行方法的方法

public class ReflectDemo7 {

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
//        Object invoke(Object obj, Object... args):运行方法
//        参数一:用obj对象调用该方法
//        参数二:调用方法的传递的参数(如果没有就不写)
//        返回值:方法的返回值(如果没有就不写)

        //1.获取class对象
        Class clazz = Class.forName("com.itbo.fanshe.StudentCon");
        //2.获取里面的Method对象  function4
        Method method = clazz.getMethod("function4", String.class);
        //3.运行function4方法就可以了
        //3.1创建一个Student对象,当做方法的调用者
        StudentCon instance = (StudentCon) clazz.newInstance();
        //3.2运行方法
        Object result = method.invoke(instance, "method");
        //4.打印一下返回值
        System.out.println(result);
    }
}

 

    心心念念的.是那割舍不断的思念.

   如果大家喜欢我的分享的话.可以关注下我的微信公众号.

   心有九月星辰

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值