0基础学java-day23(反射)

news2024/10/6 12:27:41

一、反射机制

1、一个需求引出反射

package com.hspedu.reflection.question;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;

/**
 * @author 林然
 * @version 1.0
 * 反射问题的引入
 */
@SuppressWarnings("all")
public class ReflectionQuestion {
    public static void main(String[] args) throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        //根据配置文件 re.properties 指定信息, 创建 Cat 对象并调用方法 hi
        //传统的方式 new 对象 -》 调用方法
        // Cat cat = new Cat();
        // cat.hi(); ===> cat.cry() 修改源码.
        //我们尝试做一做 -> 明白反射
        //1 使用 Properties 类, 可以读写配置文件
        Properties properties =new Properties();
        properties.load(new FileInputStream("src\\re.properties"));
        String classfullpath =properties.get("classfullpath").toString();
        String method = properties.get("method").toString();

        System.out.println("classfullpath"+classfullpath);
        System.out.println("method"+method);

        //创建对象, 传统的方法,行不通 =》 反射机制
        //new classfullpath();

        //3. 使用反射机制解决
        //(1) 加载类, 返回 Class 类型的对象 cls

        Class cls = Class.forName(classfullpath);

        //通过cls得到加载的类 com.hspedu.Cat的对象实例
        Object o =cls.newInstance();

        System.out.println("o 的运行类型=" + o.getClass()); //运行类型

        //(3) 通过 cls 得到你加载的类 com.hspedu.Cat 的 methodName"hi" 的方法对象
        // 即:在反射中,可以把方法视为对象(万物皆对象)
        Method method1 = cls.getMethod(method);

        //(4) 通过 method1 调用方法: 即通过方法对象来实现调用方法
        System.out.println("=============================");
        method1.invoke(o);

    }
}

2 反射机制 

2.1 Java Reflection 

2.2 Java 反射机制原理示意图!!!

2.3 Java 反射机制可以完成 

2.4 反射相关的主要类

package com.hspedu.reflection.question;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;

/**
 * @author 林然
 * @version 1.0
 */
public class Reflection01 {
    public static void main(String[] args) throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        //根据配置文件 re.properties 指定信息, 创建 Cat 对象并调用方法 hi
        //传统的方式 new 对象 -》 调用方法
        // Cat cat = new Cat();
        // cat.hi(); ===> cat.cry() 修改源码.
        //我们尝试做一做 -> 明白反射
        //1 使用 Properties 类, 可以读写配置文件
        Properties properties =new Properties();
        properties.load(new FileInputStream("src\\re.properties"));
        String classfullpath =properties.get("classfullpath").toString();
        String method = properties.get("method").toString();

        System.out.println("classfullpath"+classfullpath);
        System.out.println("method"+method);

        //创建对象, 传统的方法,行不通 =》 反射机制
        //new classfullpath();

        //3. 使用反射机制解决
        //(1) 加载类, 返回 Class 类型的对象 cls

        Class cls = Class.forName(classfullpath);

        //通过cls得到加载的类 com.hspedu.Cat的对象实例
        Object o =cls.newInstance();

        System.out.println("o 的运行类型=" + o.getClass()); //运行类型

        //(3) 通过 cls 得到你加载的类 com.hspedu.Cat 的 methodName"hi" 的方法对象
        // 即:在反射中,可以把方法视为对象(万物皆对象)
        Method method1 = cls.getMethod(method);

        //(4) 通过 method1 调用方法: 即通过方法对象来实现调用方法
        System.out.println("=============================");
        method1.invoke(o);
        //java.lang.reflect.Field: 代表类的成员变量, Field 对象表示某个类的成员变量
        //得到 name 字段
        //getField 不能得到私有的属性
        Field nameField = cls.getField("age");
        // 传统写法 对象.成员变量 , 反射 : 成员变量对象.get(对象)
        System.out.println(nameField.get(o));
        //java.lang.reflect.Constructor: 代表类的构造方法, Constructor 对象表示构造器
        Constructor constructor = cls.getConstructor();//()中可以指定构造器参数类型, 返回无参构造器
        System.out.println(constructor);
        Constructor constructor1 = cls.getConstructor(String.class);
        //这里老师传入的 String.class 就是 String 类的Class 对象
        System.out.println(constructor1);
    }
}

2.5 反射优点和缺点 

package com.hspedu.reflection.question;

import com.hspedu.Cat;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author 林然
 * @version 1.0
 * 测试反射调用的性能,和优化方案
 */
public class Reflection02 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        m1();
        m2();

    }
    //传统方法来调用hi
    public static void m1(){
        Cat cat =new Cat();
        long start =System.currentTimeMillis();
        for(int i=0;i<90000000;i++)
        {
            cat.hi();
        }
        long end =System.currentTimeMillis();
        System.out.println("传统方法来调用hi 耗时="+(end-start));
    }
    //反射机制来调用hi
    public static void m2() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        Class cls = Class.forName("com.hspedu.Cat");
        Object o=cls.newInstance();
        Method hi = cls.getMethod("hi");
        long start =System.currentTimeMillis();
        for(int i=0;i<90000000;i++)
        {

            hi.invoke(o);
        }
        long end =System.currentTimeMillis();
        System.out.println("反射机制来调用hi 耗时="+(end-start));
    }
}

 2.6 反射调用优化-关闭访问检查

package com.hspedu.reflection.question;

import com.hspedu.Cat;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author 林然
 * @version 1.0
 * 测试反射调用的性能,和优化方案
 */
public class Reflection02 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        m1();
        m2();
        m3();

    }
    //传统方法来调用hi
    public static void m1(){
        Cat cat =new Cat();
        long start =System.currentTimeMillis();
        for(int i=0;i<90000000;i++)
        {
            cat.hi();
        }
        long end =System.currentTimeMillis();
        System.out.println("传统方法来调用hi 耗时="+(end-start));
    }
    //反射机制来调用hi
    public static void m2() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        Class cls = Class.forName("com.hspedu.Cat");
        Object o=cls.newInstance();
        Method hi = cls.getMethod("hi");

        long start =System.currentTimeMillis();
        for(int i=0;i<90000000;i++)
        {

            hi.invoke(o);
        }
        long end =System.currentTimeMillis();
        System.out.println("m2反射机制来调用hi 耗时="+(end-start));
        //
    }
    //反射机制来调用hi
    public static void m3() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        Class cls = Class.forName("com.hspedu.Cat");
        Object o=cls.newInstance();
        Method hi = cls.getMethod("hi");
        //反射调用优化+关闭访问检查
        hi.setAccessible(true);//在反射调用方法时,取消访问检测
        long start =System.currentTimeMillis();
        for(int i=0;i<90000000;i++)
        {

            hi.invoke(o);
        }
        long end =System.currentTimeMillis();
        System.out.println("m3反射机制来调用hi 耗时="+(end-start));
        //
    }
}

二、Class类

1 基本介绍 

package com.hspedu.reflection.class_;

import com.hspedu.Cat;

/**
 * @author 林然
 * @version 1.0
 * 梳理对class类特点的梳理
 */
public class Class01 {
    public static void main(String[] args) throws ClassNotFoundException {
        //看看 Class 类图
        //1. Class 也是类,因此也继承 Object 类
        //Class
        //2. Class 类对象不是 new 出来的,而是系统创建的
            //(1) 传统 new 对象
            /* ClassLoader 类
            public Class<?> loadClass(String name) throws ClassNotFoundException {
            return loadClass(name, false);
            }
            */
       Cat cat =new Cat() ;
        //(2) 反射方式, 刚才老师没有 debug 到 ClassLoader 类的 loadClass, 原因是,我没有注销Cat cat = new Cat();
            /*
                ClassLoader 类, 仍然是通过 ClassLoader 类加载 Cat 类的 Class 对象
                public Class<?> loadClass(String name) throws ClassNotFoundException {
                return loadClass(name, false);
                }
            */
        //3. 对于某个类的 Class 类对象,在内存中只有一份,因为类只加载一次
        Class cls1 = Class.forName("com.hspedu.Cat");
        Class cls2 = Class.forName("com.hspedu.Cat");

        System.out.println(cls1.hashCode());//相同
        System.out.println(cls2.hashCode());//相同
        //Class cls3 = Class.forName("com.hspedu.Dog");
        //System.out.println(cls3.hashCode());
        Object cat1= null;
        Object cat2 = null;
        try {
            cat1 = cls1.newInstance();
            cat2 = cls2.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        System.out.println(cat1.hashCode());//不同
        System.out.println(cat2.hashCode());//不同
    }
}

 2 Class 类的常用方法

3 应用实例:

package com.hspedu.reflection.class_;

import com.hspedu.Car;

import java.lang.reflect.Field;

/**
 * @author 林然
 * @version 1.0
 * 演示Class的常用方法
 */
public class Calss02 {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchFieldException {
        String classAllPath ="com.hspedu.Car";
        //1 获取到Car对应的Class对象
        //<?> 表示不确定的 Java 类型
        Class<?> cls = Class.forName(classAllPath);
        //2 输出cls
        System.out.println(cls);//显示 cls 对象, 是哪个类的 Class 对象 com.hspedu.Car
        System.out.println(cls.getClass());//输出 cls 运行类型 java.lang.Class
        //3. 得到包名
        System.out.println(cls.getPackage().getName());//包名
        //4. 得到全类名
        System.out.println(cls.getName());
        //5. 通过 cls 创建对象实例
        Car car = (Car) cls.newInstance();
        System.out.println(car);//car.toString()
        //6. 通过反射获取属性 brand
        Field brand=cls.getField("brand");
        System.out.println(brand.get(car));
        //7. 通过反射给属性赋值
        brand.set(car,"奔驰");
        System.out.println(brand.get(car));//奔驰
        //8 我希望大家可以得到所有的属性(字段)
        System.out.println("=======所有的字段属性====");
        Field[] fields = cls.getFields();
        for (Field f : fields){
            System.out.println(f.getName());//名称
        }
    }
}

4 获取 Class 类对象 

package com.hspedu.reflection.class_;

import com.hspedu.Car;

/**
 * @author 林然
 * @version 1.0
 * 演示得到 Class 对象的各种方式(6)
 */
public class GetClass_ {
    public static void main(String[] args) throws ClassNotFoundException {
        //1. Class.forName
        String classAllPath = "com.hspedu.Car"; //通过读取配置文件获取
        Class<?> cls1 = Class.forName(classAllPath);
        System.out.println(cls1);

        //2. 类名.class , 应用场景: 用于参数传递
        Class cls2 = Car.class;
        System.out.println(cls2);

        //3. 对象.getClass(), 应用场景,有对象实例
        Car car = new Car();
        Class cls3 = car.getClass();
        System.out.println(cls3);

        //4. 通过类加载器【4 种】来获取到类的 Class 对象
            //(1)先得到类加载器 car
        ClassLoader classLoader = car.getClass().getClassLoader();
            //(2)通过类加载器得到 Class 对象
        Class cls4 = classLoader.loadClass(classAllPath);
        System.out.println(cls4);

        //cls1 , cls2 , cls3 , cls4 其实是同一个对象
        System.out.println(cls1.hashCode());
        System.out.println(cls2.hashCode());
        System.out.println(cls3.hashCode());
        System.out.println(cls4.hashCode());

        //5. 基本数据(int, char,boolean,float,double,byte,long,short) 按如下方式得到 Class 类对象
        Class<Integer> integerClass = int.class;
        Class<Character> characterClass = char.class;
        Class<Boolean> booleanClass = boolean.class;
        System.out.println(integerClass);//int

        //6. 基本数据类型对应的包装类,可以通过 .TYPE 得到 Class 类对象
        Class<Integer> type1 = Integer.TYPE;
        Class<Character> type2 = Character.TYPE; //其它包装类 BOOLEAN, DOUBLE, LONG,BYTE 等待
        System.out.println(type1);
        System.out.println(integerClass.hashCode());//?
        System.out.println(type1.hashCode());//?
    }
}

5 哪些类型有 Class 对象 

5.1 如下类型有 Class 对象

5.2 应用实例 

package com.hspedu.reflection.class_;

import java.io.Serializable;

/**
 * @author 林然
 * @version 1.0
 * 演示哪些类型有 Class 对象
 */
public class AllTypeClass {
    public static void main(String[] args) {
        Class<String> cls1 = String.class;//外部类
        Class<Serializable> cls2 = Serializable.class;//接口
        Class<Integer[]> cls3 = Integer[].class;//数组
        Class<float[][]> cls4 = float[][].class;//二维数组
        Class<Deprecated> cls5 = Deprecated.class;//注解

        Class<Thread.State> cls6 = Thread.State.class;//枚举
        Class<Long> cls7 = long.class;//基本数据类型
        Class<Void> cls8 = void.class;//void 数据类型
        Class<Class> cls9 = Class.class;//
        System.out.println(cls1);
        System.out.println(cls2);
        System.out.println(cls3);
        System.out.println(cls4);
        System.out.println(cls5);
        System.out.println(cls6);
        System.out.println(cls7);
        System.out.println(cls8);
        System.out.println(cls9);
    }
}

三、类加载

1 基本说明

2 类加载时机 

3 类加载过程图 

4 类加载各阶段完成任务 

5 加载阶段 

6 连接阶段-验证 

 7 连接阶段-准备

package com.hspedu.reflection.class_;

/**
 * @author 林然
 * @version 1.0
 * 我们说明一个类加载的链接阶段-准备
 */
public class ClassLoad02 {
    public static void main(String[] args) {

    }
}
class A{
    //属性-成员变量-字段
    //分析类加载的链接阶段-准备 属性是如何处理
    //1. n1 是实例属性, 不是静态变量,因此在准备阶段,是不会分配内存
    //2. n2 是静态变量,分配内存 n2 是默认初始化 0 ,而不是 20;在初始化阶段才会是20
    //3. n3 是 static final 是常量, 他和静态变量不一样, 因为一旦赋值就不变 n3 = 30
    public int n1 = 10;
    public static int n2 = 20;
    public static final int n3 = 30;
}

 8 连接阶段-解析

9 Initialization(初始化) 

package com.hspedu.reflection.class_;

/**
 * @author 林然
 * @version 1.0
 * 演示类加载-初始化阶段
 */
public class ClassLoad03 {
    public static void main(String[] args) {
        //1. 加载 B 类,并生成 B 的 class 对象
        //2. 链接 num = 0
        //3. 初始化阶段
        // 依次自动收集类中的所有静态变量的赋值动作和静态代码块中的语句,并合并
            /*
                clinit() {
                System.out.println("B 静态代码块被执行");
                //num = 300;
                num = 100;
                }
                合并: num = 100
            */
        //new B();//类加载
        //System.out.println(B.num);//100, 如果直接使用类的静态属性,也会导致类的加载
        //看看加载类的时候,是有同步机制控制
        /*
        protected Class<?> loadClass(String name, boolean resolve)throws ClassNotFoundException
            {
            //正因为有这个机制,才能保证某个类在内存中, 只有一份 Class 对象
            synchronized (getClassLoadingLock(name)) {
            //.... }
            }
         */
        B b = new B();
    }
}
class B{
    static {
        System.out.println("B 静态代码块被执行");
        num = 300;
    }
    static int num = 100;
    public B() {//构造器
        System.out.println("B() 构造器被执行");
    }
}

四、反射获取类的结构信息

1 第一组: java.lang.Class

 2 第二组: java.lang.reflect.Field

3 第三组: java.lang.reflect.Method  

 4 第四组: java.lang.reflect.Constructor

package com.hspedu.reflection;

import org.junit.Test;

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @author 林然
 * @version 1.0
 * 演示如何通过反射获取类的结构信息
 */
public class ReflectionUtils {
    public static void main(String[] args) {

    }
    //第一组方法 API
    @Test
    public void api_01() throws ClassNotFoundException {
        //得到Class对象
        Class<?> personCls = Class.forName("com.hspedu.reflection.Person");
        //getName:获取全类名
        System.out.println(personCls.getName());//com.hspedu.reflection.Person
        //getSimpleName:获取简单类名
        System.out.println(personCls.getSimpleName());//Person
        //getFields:获取所有 public 修饰的属性,包含本类以及父类的
        Field[] fields = personCls.getFields();
        for(Field field :fields)
        {
            System.out.println("本类以及父类的属性:"+field.getName());
        }
        //getDeclaredFields:获取本类中所有属性
        Field[] declaredFields = personCls.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            System.out.println("本类中所有属性="+declaredField.getName());
        }
        //getMethods:获取所有 public 修饰的方法,包含本类以及父类的【不局限于直接父类
        Method[] methods = personCls.getMethods();
        for (Method method : methods) {
            System.out.println("本类以及父类的方法="+method.getName());
        }
        //getDeclaredMethods:获取本类中所有方法
        Method[] declaredMethods = personCls.getDeclaredMethods();
        for (Method declaredMethod : declaredMethods) {
            System.out.println("本类中所有方法=" + declaredMethod.getName());
        }
        //getConstructors: 获取所有 public 修饰的构造器,包含本类
        Constructor<?>[] constructors = personCls.getConstructors();
        for (Constructor<?> constructor : constructors) {
            System.out.println("本类的构造器=" + constructor.getName());
        }
        //getDeclaredConstructors:获取本类中所有构造器
        Constructor<?>[] declaredConstructors = personCls.getDeclaredConstructors();
        for (Constructor<?> declaredConstructor : declaredConstructors) {
            System.out.println("本类中所有构造器=" + declaredConstructor.getName());//这里老师只是输出名
        }
        //getPackage:以 Package 形式返回 包信息
        System.out.println(personCls.getPackage());//com.hspedu.reflection
        //getSuperClass:以 Class 形式返回父类信息
        Class<?> superclass = personCls.getSuperclass();
        System.out.println("父类的 class 对象=" + superclass);//
        //getInterfaces:以 Class[]形式返回接口信息
        Class<?>[] interfaces = personCls.getInterfaces();
        for (Class<?> anInterface : interfaces) {
            System.out.println("接口信息=" + anInterface);
        }
        //getAnnotations:以 Annotation[] 形式返回注解信息
        Annotation[] annotations = personCls.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println("注解信息=" + annotation);//注解
        }
    }
    @Test
    public void api_02() throws ClassNotFoundException {
        //得到 Class 对象
        Class<?> personCls = Class.forName("com.hspedu.reflection.Person");
        //getDeclaredFields:获取本类中所有属性
        //规定 说明: 默认修饰符 是 0 , public 是 1 ,private 是 2 ,protected 是 4 , static 是 8 ,final 是 16
        Field[] declaredFields = personCls.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            System.out.println("本类中所有属性=" + declaredField.getName()+
                    " 该属性的修饰符值=" + declaredField.getModifiers()
                    + " 该属性的类型=" + declaredField.getType());

        }

        //getDeclaredMethods:获取本类中所有方法
        Method[] declaredMethods = personCls.getDeclaredMethods();
        for (Method declaredMethod : declaredMethods) {
            System.out.println("本类中所有方法=" + declaredMethod.getName()
                    + " 该方法的访问修饰符值=" + declaredMethod.getModifiers()
                    + " 该方法返回类型" + declaredMethod.getReturnType());
            //输出当前这个方法的形参数组情况
            Class<?>[] parameterTypes = declaredMethod.getParameterTypes();
            for (Class<?> parameterType : parameterTypes) {
                System.out.println("该方法的形参类型=" + parameterType);
            }
        }

        //getDeclaredConstructors:获取本类中所有构造器
        Constructor<?>[] declaredConstructors = personCls.getDeclaredConstructors();
        for (Constructor<?> declaredConstructor : declaredConstructors) {
            System.out.println("====================");
            System.out.println("本类中所有构造器=" + declaredConstructor.getName());//这里老师只是输出名
            Class<?>[] parameterTypes = declaredConstructor.getParameterTypes();
            for (Class<?> parameterType : parameterTypes) {
                System.out.println("该构造器的形参类型=" + parameterType);
            }
        }
    }
}
interface IA {
}
interface IB {
}
class A{
    public String hobby;
    public void hi() {
    }
    public A() {
    }
    public A(String name) {
    }
}
@Deprecated
class Person extends A implements IA,IB{
    //属性
    public String name;
    protected static int age; // 4 + 8 = 12
    String job;
    private double sal;
    //构造器
    public Person() {
    }
    public Person(String name) {
    }
    //私有的
    private Person(String name, int age) {
    }
    //方法
    public void m1(String name, int age, double sal) {
    }
    protected String m2() {
        return null;
    }
    void m3() {
    }
    private void m4() {
    }
}

五、通过反射创建对象

案例演示: 

package com.hspedu.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @author 林然
 * @version 1.0
 * 演示通过反射机制创建实例
 */
public class ReflecCreateInstance {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        //1. 先获取到 User 类的 Class 对象
        Class<?> userClass = Class.forName("com.hspedu.reflection.User");
        //2. 通过 public 的无参构造器创建实例
        Object o=userClass.newInstance();
        System.out.println(o);
        //3. 通过 public 的有参构造器创建实例
        /*
            constructor 对象就是
            public User(String name) {//public 的有参构造器
            this.name = name;
            }
        */
        //3.1 先得到对应构造器
        Constructor<?> constructor = userClass.getConstructor(String.class);
        //3.2 创建实例,并传入实参
        Object lin = constructor.newInstance("琳琳");
        System.out.println("lin=" + lin);

        //4. 通过非 public 的有参构造器创建实例
        //4.1 得到 private 的构造器对象
        Constructor<?> declaredConstructor = userClass.getDeclaredConstructor(int.class, String.class);
        //4.2 创建实例
        //暴破【暴力破解】 , 使用反射可以访问 private 构造器/方法/属性, 反射面前,都是纸老虎
        declaredConstructor.setAccessible(true);
        Object liming = declaredConstructor.newInstance(18, "黎明");
        System.out.println("liming="+liming);


    }
}
class User { //User 类
    private int age = 10;
    private String name = "林然";
    public User() {//无参 public
    }
    public User(String name) {//public 的有参构造器
        this.name = name;
    }
    private User(int age, String name) {//private 有参构造器
        this.age = age;
        this.name = name;
    }
    public String toString() {
        return "User [age=" + age + ", name=" + name + "]";
    }
}

六、通过反射访问类中的成员

1 访问属性 ReflecAccessProperty.java

package com.hspedu.reflection;

import java.lang.reflect.Field;

/**
 * @author 林然
 * @version 1.0
 * 演示反射操作属性
 */
public class ReflecAccessProperty {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchFieldException {
        //1. 得到 Student 类对应的 Class 对象
        Class<?> StuClass = Class.forName("com.hspedu.reflection.Student");
        //2. 创建对象
        Object o = StuClass.newInstance();//o 的运行类型就是 Student
        System.out.println(o.getClass());//Student
        //3. 使用反射得到 age 属性对象
        Field age = StuClass.getField("age");
        age.set(o,88);//通过反射来操作属性
        System.out.println(o);//
        System.out.println(age.get(o));//返回 age 属性的值
        //4. 使用反射操作 name 属性
        Field name = StuClass.getDeclaredField("name");
        //对 name 进行暴破, 可以操作 private 属性
        name.setAccessible(true);
        name.set(0,"林然");
        System.out.println(o);
        name.set(null, "老刘~");//因为 name 是 static 属性,因此 o 也可以写出 null
        System.out.println(o);
        System.out.println(name.get(o)); //获取属性值
        System.out.println(name.get(null));//获取属性值, 要求 name 是 static

    }
}
class Student{
    public int age;
    private static String name;
    public Student() {//构造器
    }
    public String toString() {
        return "Student [age=" + age + ", name=" + name + "]";
    }
}

 2 访问方法 ReflecAccessMethod.java

package com.hspedu.reflection;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author 林然
 * @version 1.0
 * 演示通过反射调用方法
 */
public class ReflecAccessMethod {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        //1. 得到 Boss 类对应的 Class 对象
       Class<?> bossCls = Class.forName("com.hspedu.reflection.Boss");
        //2. 创建对象
        Object o = bossCls.newInstance();
        //3. 调用 public 的 hi 方法
        //Method hi = bossCls.getMethod("hi", String.class);//OK
        //3.1 得到 hi 方法对象
        Method hi = bossCls.getDeclaredMethod("hi", String.class);//OK
        //3.2 调用
        hi.invoke(o, "林然~");
        //4. 调用 private static 方法
        //4.1 得到 say 方法对象
        Method say = bossCls.getDeclaredMethod("say", int.class, String.class, char.class);
        //4.2 因为 say 方法是 private, 所以需要暴破,原理和前面讲的构造器和属性一样
        say.setAccessible(true);
        System.out.println(say.invoke(o, 100, "张三", '男'));
        //4.3 因为 say 方法是 static 的,还可以这样调用 ,可以传入 null
        System.out.println(say.invoke(null, 200, "李四", '女'));
        //5. 在反射中,如果方法有返回值,统一返回 Object , 但是他运行类型和方法定义的返回类型一致
        Object reVal = say.invoke(null, 300, "王五", '男');
        System.out.println("reVal 的运行类型=" + reVal.getClass());//String
        //在演示一个返回的案例
        Method m1 = bossCls.getDeclaredMethod("m1");
        Object reVal2 = m1.invoke(o);
        System.out.println("reVal2 的运行类型=" + reVal2.getClass());//Monster

    }
}
class Monster {}
class Boss{
    public int age;
    private static String name;
    public Boss() {//构造器
    }
    public Monster m1() {
        return new Monster();
    }
    private static String say(int n, String s, char c) {//静态方法
        return n + " " + s + " " + c;
    }
    public void hi(String s){
        System.out.println("hi " + s);
    }
}

七、本章作业

1.作业一

package com.hspedu.homework;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author 林然
 * @version 1.0
 */
public class Homework01 {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchFieldException, NoSuchMethodException, InvocationTargetException {
        Class<?> aClass = Class.forName("com.hspedu.homework.PrivateTest");
        Object o = aClass.newInstance();
        Field name = aClass.getDeclaredField("name");
        name.setAccessible(true);
        name.set(o,"linran");
        //System.out.println(name.get(o));
       Method getName = aClass.getMethod("getName");
       System.out.println(getName.invoke(o));
    }
}
class PrivateTest{
    private String name="hello林然";

    public String getName() {
        return name;
    }
}

2.作业二

package com.hspedu.homework;

import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author 林然
 * @version 1.0
 */
public class Homework02 {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        Class<?> fileClass = Class.forName("java.io.File");
        Constructor<?>[] declaredConstructors = fileClass.getDeclaredConstructors();
        for (Constructor<?> declaredConstructor : declaredConstructors) {
            System.out.println("File的构造器="+declaredConstructor.getName());
        }
        Constructor<?> declaredConstructor = fileClass.getDeclaredConstructor(String.class);
        String fileAllPath="e:\\mynew.txt";
        Object fiel = declaredConstructor.newInstance(fileAllPath);//创建了File对象
        Method createNewFile = fileClass.getMethod("createNewFile");
        createNewFile.invoke(fiel);//创建文件成功
        


    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1352249.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

努力打工的你存到钱了?2024新蓝海创业项目/适合普通人创业项目

为什么有钱人那么有钱&#xff1f;是他们够努力吗&#xff1f;有一位网友回答是这样回答的&#xff1a; “从小到大我所接触到的一切成功&#xff0c;他的基础都是努力&#xff0c;甚至于奉承时的吃得苦上苦方为人上人。但是那天我的三观出现了认知错误&#xff0c;光靠努力赚…

python c语言 代码动态检查,python c语言语法分析

大家好&#xff0c;小编来为大家解答以下问题&#xff0c;python c语言 代码动态检查&#xff0c;python c语言语法分析&#xff0c;今天让我们一起来看看吧&#xff01; Source code download: 本文相关源码 初学编程&#xff0c;应该学习哪一门编程语言&#xff0c;有不少人感…

02--数据定义语言DDL

1、数据定义语言DDL 1.1 操作数据库-DDL 创建数据库 create database 数据库名称; 创建数据库&#xff0c;并指定字符集 create database 数据库名称 character set 字符集名; 查询所有数据库的名称 show databases; 查询某个数据库的字符集:查询某个数据库的创建语句及字…

二、Redis的特性与应用场景

Redis是一个在内存中存储数据的中间件&#xff0c;主要用于作为数据库、数据缓存&#xff0c;在分布式系统中有着非常重要的地位。面试中可以围绕Redis的特性进行介绍。 一、Redis特性 1、在内存中存储数据 MySQL主要是“表”的方式来存储组织数据的&#xff0c;是“关系型数…

聚醚胺市场分析:预计到2025年将达到10亿美元

聚醚胺是一种有机化合物&#xff0c;在涂料、胶粘剂、树脂等多种行业中用作固化剂、缓蚀剂和燃料添加剂。由于对广泛用于建筑和汽车行业的聚脲涂料的需求不断增加&#xff0c;全球聚醚胺市场一直在经历显着增长。 全球市场分析&#xff1a; 2020 年全球聚醚胺市场价值为 6.2 亿…

【竞技宝】LOL:S14新赛季改动 将trueskill2隐藏分算法

北京时间2024年1月3日,随着英雄联盟德玛西亚杯的进行,英雄联盟赛事已经进入新赛季的征途。每个赛季的春季赛之前,都会进行一次大的版本更新。据爆料,今年的S14版本大更新中,除了游戏内的英雄、道具、地图的更新之外,排位的隐藏分算法也将进行重大改变。 昨日,英雄联盟设计总监…

c++ 静态联编+动态联编 (多态)

静态多态 动态多态 1&#xff09;静态多态和动态多态的区别就是函数地址是早绑定(静态联编)还是晚绑定(动态联编)。 如果函数的调用&#xff0c;在编译阶段就可以确定函数的调用地址&#xff0c;并产生代码&#xff0c;就是静态多态(编译时多态)&#xff0c;就是说地址是早绑定…

Android Studio 报错AAPT: error: resource android:attr/lStar not found.解决方法!

目录 前言 一、报错信息 二、解决方法 三、常见处理方法总结 四、更多资源 前言 在快速发展的科技领域中&#xff0c;移动应用开发已经成为了一个非常热门的领域。而作为开发Android应用的主要工具之一&#xff0c;Android Studio 提供了丰富的功能和工具来帮助开发者构建…

c语言和python区别哪个难,c语言和python区别大不大

大家好&#xff0c;给大家分享一下c语言和python区别主要用来写什么&#xff0c;很多人还不知道这一点。下面详细解释一下。现在让我们来看看&#xff01; Python可以说是目前最火的语言之一了&#xff0c;人工智能的兴起让Python一夜之间变得家喻户晓&#xff0c;Python号称目…

BMS均衡技术

一、电池的不一致性&#xff1f; 每个电池都有自己的“个性”&#xff0c;要说均衡&#xff0c;得先从电池谈起。即使是同一厂家同一批次生产的电池&#xff0c;也都有自己的生命周期、自己的“个性”——每个电池的容量不可能完全一致。例如以下的两个原因都会造成电池不一致…

【零基础入门TypeScript】TypeScript - 基本语法

目录 你的第一个 TypeScript 代码 编译并执行 TypeScript 程序 编译器标志 TypeScript 中的标识符 TypeScript ─ 关键字 空格和换行符 TypeScript 区分大小写 分号是可选的 TypeScript 中的注释 TypeScript 和面向对象 语法定义了一组编写程序的规则。每种语言规范都…

浏览器使用隧道代理HTTP:洞悉无界信息

在信息爆炸的时代&#xff0c;互联网已经成为获取信息的首选渠道。然而&#xff0c;在某些地区或情况下&#xff0c;访问某些网站可能会受到限制。这时&#xff0c;隧道代理HTTP便成为了一个重要的工具&#xff0c;帮助用户突破限制&#xff0c;洞悉无界信息。 一、隧道代理HT…

Nextjs打包类型检查报错ype error: Property ‘card_list‘ does not exist on type(已解决)

在Nextjs 中 在数组 map 的时候报错如下: 里面的数据类型是 data1 {cart_list:[]} 那么在 声明类型的时候 使用 data1:{card_list:any[]} export default function Card({authStates,data1,data2}:{authStates:boolean;data1:{card_list:any[]};data2:any[]}) {}) 这样就…

学到了!3步get微信自动回复

你是不是也有过这样的烦恼&#xff1a;因为忙碌或是消息太多&#xff0c;没能及时回复好友消息&#xff0c;尤其是在休息、节假日的时候。 今天就给大家种草一款能够让微信自动回复消息的神器——微信管理系统&#xff0c;让你再忙碌也能及时回复好友&#xff01;而且操作也不…

YOLOv8改进 | 检测头篇 | DynamicHead原论文一比一复现 (不同于网上版本,全网首发)

一、本文介绍 本文给大家带来的改进机制是DynamicHead(Dyhead),这个检测头由微软提出的一种名为“动态头”的新型检测头,用于统一尺度感知、空间感知和任务感知。网络上关于该检测头我查了一些有一些魔改的版本,但是我觉得其已经改变了该检测头的本质,因为往往一些细节上才…

互联网加竞赛 基于LSTM的天气预测 - 时间序列预测

0 前言 &#x1f525; 优质竞赛项目系列&#xff0c;今天要分享的是 机器学习大数据分析项目 该项目较为新颖&#xff0c;适合作为竞赛课题方向&#xff0c;学长非常推荐&#xff01; &#x1f9ff; 更多资料, 项目分享&#xff1a; https://gitee.com/dancheng-senior/po…

【性能测试】性能压测TPS上不去原因分析,13年老鸟总结...

目录&#xff1a;导读 前言一、Python编程入门到精通二、接口自动化项目实战三、Web自动化项目实战四、App自动化项目实战五、一线大厂简历六、测试开发DevOps体系七、常用自动化测试工具八、JMeter性能测试九、总结&#xff08;尾部小惊喜&#xff09; 前言 1、性能测试TPS上…

数据结构学习 jz42连续子数组最大和

关键词&#xff1a;动态规划 滚动数组 最长上升子序列 这道题比较简单&#xff0c;类似最长上升子序列&#xff0c;比最长上升子序列简单。 和最长上升子序列的区别&#xff1a;这道题因为是连续的&#xff0c;所以只用记录max就好了。最长上升子序列是不连续的&#xff0c;所…

【计算机毕业设计】SSM实现的在线农产品商城

项目介绍 本项目分为前后台&#xff0c;且有普通用户与管理员两种角色。 用户角色包含以下功能&#xff1a; 用户登录,查看首页,按分类查看商品,查看新闻资讯,查看关于我们,查看商品详情,加入购物车,查看我的订单,提交订单,添加收获地址,支付订单等功能。 管理员角色包含以…

TypeScript 之 interface 和 type 的区别

结论&#xff1a; 1、可以声明的数据类型 type 可以修饰任何类型 &#xff08;值类型和引用数据类型&#xff09; interface 只能修饰引用类型 &#xff08;对象、数组、函数&#xff09; //interface 声明对象属性 interface ins {a: string;b?: number; //可选项 }// int…