一篇彻底搞懂Java的反射机制

本文详细介绍了Java反射机制,包括Class类、类加载器、newInstance()方法以及如何获取运行时类的结构。通过实例展示了如何创建对象、访问私有属性和方法,强调了反射的动态性。此外,还讨论了何时使用反射,如动态代理和Servlet。文章涵盖了反射在实际开发中的应用场景,如动态代理和接口实现的灵活性。
摘要由CSDN通过智能技术生成

Java反射


首先介绍一下反射:
 加载完类以后,在堆内存的方法区中,就产生了一个Class类型的对象(一个类只有一个Class对象),这个对象包含了完整的类的结构信息,我们可以通过这个对象看到类的结构。 这个对象就像一面镜子,透过这个镜子看到类的结构,所以,形象的称之为“反射”。

 话不多说,我们先来看一个反射的例子,看看反射能做什么,看看热闹。如果你从来没了解过反射的话,这段代码粗略的看看注释就好了。
实例代码:
pojo类

/**
 * @author zrulin
 * @create 2022-04-09 21:18
 */public class Dog {
    private String name;
    public Integer age;

    public Dog() {
    }
    private Dog(String name){
        this.name = name;
    }

    public Dog(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

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

    public void speak(){
        System.out.println("汪汪!");
    }

    private String see(String obj){
        System.out.println("我看见了"+obj+"!");
        return obj + "真好看";
    }

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

操作对象:

/**
 * @author zrulin
 * @create 2022-04-09 21:17
 */
public class ReflectTest {
    //反射之前:对Dog的操作
    @Test
    public void test(){

        Dog dog = new Dog("小付",3);
        dog.age = 2;

        dog.speak();
        System.out.println(dog);
    }

    //反射之后,对dog的操作
    @Test
    public void test1() throws Exception{
        Class clazz = Dog.class;
        //通过反射创建Dog对象
        Constructor constructor = clazz.getConstructor(String.class, Integer.class);
        Dog dog = (Dog) constructor.newInstance("小勇", 5);

        System.out.println(dog);
        //通过反射调用对象指定的属性,方法
        Field age = clazz.getDeclaredField("age");
        age.set(dog,3);

        System.out.println(dog);
        //调用方法
        Method speak = clazz.getDeclaredMethod("speak");
        speak.invoke(dog);

        //通过反射,可以调用Dog的私有结构,比如,私有的构造器,方法,属性。
        //调用私有的构造器。
        Constructor constructor1 = clazz.getDeclaredConstructor(String.class);
        constructor1.setAccessible(true);
        Dog dog1 = (Dog) constructor1.newInstance("小军");
        System.out.println(dog1);

        //调用私有的属性
        Field name = clazz.getDeclaredField("name");
        name.setAccessible(true);
        name.set(dog,"小军");
        System.out.println(dog);

        //调用私有的方法
        Method showSee = clazz.getDeclaredMethod("see",String.class);
        showSee.setAccessible(true);
        String temp = (String) showSee.invoke(dog,"美女");
        System.out.println(temp);


    }
}

使用到的API:
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

 在这个代码中使用反射不但能干之前对类的一些操作,还可以干之前干不了的事。

  • 那我们什么时候会用到反射呢?
    示例一:动态代理的时候,进行aop切面的操作,对方法进行增强。
    示例二:sevlet通过你的路径比如是 ‘/login’ 或者是 ‘/index’ 去构造对应的对象,调用相关的方法。sevlet在事先是不知道要实例化哪些对象的。在运行的时候动态的创建。
    反射的特征:动态性。

java.lang.Class

  • 关于Java.lang.Class类的理解
    1、类的加载过程:
     程序经过javac.exe命令之后会生成一个或多个字节码文件(.class结尾)。
     接着我们使用java.exe对某个字节码文件进行解释运行。相当于你把某个字节码文件加载到内存中,此过程就称为类的加载。加载到内存中的,我们就称之为运行时类,此运行时类,就作为Class的一个实例。
    2、换句话说,Class实例就对应着一个运行时类。
     加载到内存中的运行时类,会缓存一定的时间,在此时间内,我们可以通过不同的方式来获取此运行时类。

获取Class实例的方法:

public class ReflectTest {
    @Test
    public void test2() throws ClassNotFoundException {
        //方式一:调用运行时类的属性: .class
        Class clazz1 = Dog.class;
        System.out.println(clazz1);

        //方式二:调用运行时类的对象,调用getClass()
        Dog dog = new Dog();
        Class clazz2 = dog.getClass();
        System.out.println(clazz2);

        //方式三:调用Class的静态方法:forName("zrulin.pojo.Dog");
        //System.out.println(Class.forName("java.lang.String"));
        Class clazz3 = Class.forName("zrulin.pojo.Dog");
        System.out.println(clazz3);

        //方式四:使用类加载器
        ClassLoader classLoader = ReflectTest.class.getClassLoader();
        Class clazz4 = classLoader.loadClass("zrulin.pojo.Dog");
        System.out.println(clazz4);


        System.out.println(clazz1 == clazz2);
        System.out.println(clazz2 == clazz3);
        System.out.println(clazz3 == clazz4);
    }
}

那么具体哪些类型可以有class对象呢?

  1. class : 外部类,成员(成员内部类,静态内部类),局部内部类,匿名内部类,
  2. interface : 接口
  3. [] : 数组 —>只要数组的维度和类型一样,就是同一个Class
  4. enum: 枚举
  5. annotation : 注解 @interface
  6. primitive type : 基本数据类型
  7. void

类加载器(ClassLoader)

类加载器(ClassLoader)的理解:

  • 类加载的作用:
     将class文件字节码内容加载到内存中,并将这些静态数据转换成方法区的运行时数据结构,然后再堆中生成一个代表这个类的 java.lang.Class 对象,作为方法区中类数据的访问入口。
  • 类缓存
      标准的JavaSE类加载器可以按照要求查找类,但一旦某个类被加载到类加载器中,他将维持加载(缓存)一段时间。不过jvm的回收机制可以回收这些Class对象。

类加载器读取配置文件:

    @Test
    public void test3()throws Exception{
        Properties properties = new Properties();

        //读取配置文件方式一:
        //此时的文件默认再module下。
//        FileInputStream inputStream = new FileInputStream("jdbc.properties");
//        properties.load(inputStream);

        //读取配置文件方式二:使用ClassLoader
        //配置文件默认识别为:当前module的src下。
        InputStream is = ReflectTest.class.getClassLoader().getResourceAsStream("jdbc1.properties");
        properties.load(is);

        String name = properties.getProperty("name");
        String pwd = properties.getProperty("password");
        System.out.println(name + ":"+pwd);
    }

newInstance()

newInstance():调用此方法,创建对应运行时类的对象,内部调用了运行时类的空参构造器
想要此方法正常的创建运行时类的对象,要求:

  1. 运行时类必须提供空参的构造器
  2. 空参的构造器的权限得够,通常,设置为public
    @Test
    public void test4() throws InstantiationException, IllegalAccessException {
        Class<Dog> clazz = Dog.class;

        //在JavaBean中要求提供一个public的空参构造器,原因:
        //1、便于通过反射,创建运行时类的对象
        //2、便于子类继承此运行时类时,默认调用super()时,保证父类有此构造器。
        Dog dog = clazz.newInstance();
        System.out.println(dog);
    }

用代码来体验反射的动态性:

 @Test
    public void test5(){
        for (int j = 0; j < 20; j++) {
            int i = new Random().nextInt(3);
            String ClassPath = "";
            switch (i){
                case 0:ClassPath = "java.util.Date";
                    break;
                case 1:ClassPath = "java.lang.Object";
                    break;
                case 2:ClassPath = "zrulin.pojo.Dog";
                    break;
            }
            try {
                System.out.println(getInstance(ClassPath));
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    public Object getInstance(String ClassPath) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        return Class.forName(ClassPath).newInstance();
    }

这里在编译的时候不确定使用哪一个类的,只有在运行的时候才动态的知道用到的是哪一个类。

获取运行时类的完整结构

首先把我要用到的javabean 代码附上:

/**
 * 自定义注解
 * @author zrulin
 * @create 2022-04-11 20:51
 */
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    String value() default "hello";
}


/**
 * 自定义接口
 * @author zrulin
 * @create 2022-04-11 20:46
 */
public interface MyInterface {
    void info();
}

/**
 * 要用到的父类
 * @author zrulin
 * @create 2022-04-11 20:44
 */
public class Creature<T> implements Serializable {
    private char gender;
    public double weight;

    private void breath(){
        System.out.println("生物呼吸");
    }
    public void eat(){
        System.out.println("生物进食");
    }
}

/**
 * @author zrulin
 * @create 2022-04-11 20:46
 */
@MyAnnotation(value = "hi")
public class Person extends Creature<String> implements Comparable<String>,MyInterface{

    private String name;
    int age;
    public int id;

    public Person(){};

    private Person(String name){
        this.name = name;
    }
    Person(String name, int age){
        this.name = name;
        this.age = age;
    }

    @MyAnnotation
    private String show(String nation){
        System.out.println("我的国籍是" + nation);
        return nation;
    }
    public String display(String interests, int age)throws IOException, RuntimeException {
        return interests;
    }
    public static void showDesc(){
        System.out.println("我是一个好人");
    }

    @Override
    public int compareTo(String o) {
        return 0;
    }

    @Override
    public void info() {
        System.out.println("我是一个人");
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", id=" + id +
                '}';
    }
}

重头戏来咯:

  • 获取当前类的属性结构。以及单独获取权限修饰符,数据类型,变量名。(获取细节用的比较少,了解一下即可)
   //获取当前运行时类的属性结构
    @Test
    public void FieldTest(){
        Class<Person> clazz = Person.class;

        //获取属性结构
        Field[] fields = clazz.getFields();
        for (Field field : fields) {
            System.out.println(field);
        }
        /*结果:
            public int zrulin.pojo.Person.id
            public double zrulin.pojo.Creature.weight
          结论:
            getFields()可以获得当前运行时类及其父类中,声明为public访问权限的属性。
         */

        Field[] fields1 = clazz.getDeclaredFields();
        for (Field field : fields1) {
            System.out.println(field);
        }
        /*结果:
            private java.lang.String zrulin.pojo.Person.name
            int zrulin.pojo.Person.age
            public int zrulin.pojo.Person.id
          结论:
            获取当前运行时类中声明的所有属性。(不包含父类中声明的属性)
         */
    }

    //获取属性结构中具体的内容,如:权限修饰符,数据类型,变量名。
    @Test
    public void FieldTest1(){
        Class<Person> clazz = Person.class;
        Field[] fields1 = clazz.getDeclaredFields();
        for (Field field : fields1) {
            //1、权限修饰符, modifier中 0-默认权限,1-public, 2-private
            int modifier = field.getModifiers();
            //使用Modifier.toString()方法直接获取英文。
            System.out.printf(Modifier.toString(modifier) + "\t");
            //2、数据类型
            Class type = field.getType();
            System.out.printf(type.getName() + "\t");
            //3、变量名
            String name = field.getName();
            System.out.println(name);
        }
    }
  • 通过反射拿到方法结构,以及里面的细节。(获取内部细节这个事,平时也很少用到,了解即可)
 //获取运行时类的方法结构。
    @Test
    public void MethodTest(){
        Class clazz = Person.class;

        //getMethods():获取当前运行时类及其所有父类中声明为public权限的方法。
        Method[] methods = clazz.getMethods();
        for (Method method : methods) {
            System.out.println(method);
        }
        System.out.println("------------------------------");

        //getDeclaredMethods():获取当前运行时类中声明的所有方法,(不包含父类中声明的)
        Method[] methods1 = clazz.getDeclaredMethods();
        for (Method method : methods1) {
            System.out.println(method);
        }
    }

    //获取运行时类中方法结构中的具体结构。
    /*
    @Xxxx
    权限修饰符  返回值类型  方法名(参数类型1 形参名1, ...)throws XxxException{}
     */
    @Test
    public void MethodTest1(){
        Class clazz = Person.class;
        Method[] methods1 = clazz.getDeclaredMethods();
        for (Method method : methods1) {
            //获取方法声明的注解
            Annotation[] annotations = method.getAnnotations();
            for (Annotation annotation : annotations) {
                System.out.println(annotation);
            }
            //1、权限修饰符
            int modifiers = method.getModifiers();
            System.out.printf(  Modifier.toString(modifiers) + "\t");

            //2、返回值类型
            System.out.printf(method.getReturnType().getName() + "\t");

            //3、方法名(参数类型1 形参名1, ...)
            System.out.print(method.getName());
            System.out.print("(");
            //形参列表
            Class[] parameterTypes = method.getParameterTypes();
            if(!(parameterTypes == null || parameterTypes.length == 0)){
                for (int i = 0; i < parameterTypes.length; i++){
                    if(i == parameterTypes.length -1){
                        System.out.print(parameterTypes[i].getName() + "args_" + i);
                        break;
                    }
                    System.out.print(parameterTypes[i].getName() + "args_" + i + ",");
                }
            }
            System.out.print(")");
            //抛出的异常
            Class[] exceptionTypes = method.getExceptionTypes();
            if(!(exceptionTypes == null || exceptionTypes.length == 0)){
                System.out.print("throws ");
                for (int i = 0; i < exceptionTypes.length; i++){
                    if(i == exceptionTypes.length -1){
                        System.out.print(exceptionTypes[i].getName());
                        break;
                    }
                    System.out.print(exceptionTypes[i].getName()+",");
                }
            }
            System.out.println();
        }
    }
  • 获取构造器结构。具体细节也能获取,但不再演示。
    /**
     * 获取构造器结构
     */
    @Test
    public void ConstructorTest(){
        Class clazz = Person.class;

        //getConstructors():获取当前运行时类中声明为public的构造器
        Constructor[] constructors = clazz.getConstructors();
        for (Constructor constructor : constructors) {
            System.out.println(constructor);
        }

        //getDeclaredConstructors():获取当前运行时类中声明的所有的构造器。
        Constructor[] constructors1 = clazz.getDeclaredConstructors();
        for (Constructor constructor : constructors1) {
            System.out.println(constructor);
        }
    }
  • 获取运行时类的父类结构
 //获取运行时类的父类
    @Test
    public void ParentTest(){
        Class clazz = Person.class;

        Class superclass = clazz.getSuperclass();
        System.out.println(superclass);


        //获取带泛型的父类
        Type genericSuperclass = clazz.getGenericSuperclass();
        System.out.println(genericSuperclass);

        //获取带泛型的父类的泛型
        Type genericSuperclass1 = clazz.getGenericSuperclass();
        //强转成一个带参数的类型
        ParameterizedType paramType = (ParameterizedType) genericSuperclass1;
        //getActualArgument获取实际上的参数
        Type[] actualTypeArguments = paramType.getActualTypeArguments();
        for (Type actualTypeArgument : actualTypeArguments) {
            //getTypeName只获得名字
            System.out.println(actualTypeArgument.getTypeName());
        }
  • 获取运行时类实现的接口,所在的包,声明的注解
    //获取运行时类实现的接口
    @Test
    public void InterfaceTest(){
        Class clazz = Person.class;

        //获取当前运行时类实现的接口
        Class[] interfaces = clazz.getInterfaces();
        for (Class anInterface : interfaces) {
            System.out.println(anInterface);
        }
        //获取运行时类的   父类实现的接口
        Class[] interfaces1 = clazz.getSuperclass().getInterfaces();
        for (Class aClass : interfaces1) {
            System.out.println(aClass);
        }
    }

    //获取当前运行时类所在的包
    @Test
    public void packageTest(){
        Class clazz = Person.class;
        Package aPackage = clazz.getPackage();
        System.out.println(aPackage);
    }

    //获取当前运行时类声明的注解
    @Test
    public void annotationTest(){
        Class clazz = Person.class;
        Annotation[] annotations = clazz.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println(annotation);
        }
    }

获取运行时类的指定结构

这里使用的还是上述的bean对象。

  • 调用运行时类中指定属性
  /*
    操作运行时类指定属性
     */
    @Test
    public void getField() throws NoSuchFieldException, InstantiationException, IllegalAccessException {
        Class<Person> clazz = Person.class;

        //创建运行时类的对象
        Person person = clazz.newInstance();

        //getField()获取指定属性,要求属性声明为public
        //通常不采用此方法
        Field id = clazz.getField("id");//public
        id.set(person,101);//参数:(要设置的对象,值)
        int Pid = (int) id.get(person);//参数(获取的对象)
        System.out.println(Pid);
        System.out.println("------------------------");


        //getDeclaredField():能获取到除public的其他权限的属性,但需要手动设置允许访问setAccessible(true);
        Field age = clazz.getDeclaredField("age");
        //保证当前属性是可访问的。
        age.setAccessible(true);
        //根据需求改动属性
        age.set(person,5);
        int Page = (int) age.get(person);
        System.out.println(Page);
    }
  • 调用运行时类的指定方法:
    /*
  操作运行时类指定方法
   */
    @Test
    public void getMethod() throws Exception {
        Class<Person> clazz = Person.class;
        Person person = clazz.newInstance();

        //获取指定的某个方法:
        // clazz.getDeclaredMethod("show", String.class):参数1:指明要获取的方法名称,参数2:获取的方法的形参列表
        Method show = clazz.getDeclaredMethod("show", String.class);
        //保证当前方法是可访问的
        show.setAccessible(true);
        //invoke(person,"中国"):参数1:方法的调用者,参数二:给方法形参赋值的实参。
        //invoke方法的返回值,即对应方法的返回值。
        String nation = (String) show.invoke(person,"中国");
        System.out.println(nation);

        System.out.println("-----------------如何调用静态方法---------------------");
        Method showDesc = clazz.getDeclaredMethod("showDesc");
        showDesc.setAccessible(true);
        //静态方法这里可以直接写null,写不写方法的调用者都行。
        showDesc.invoke(null);
    }
  • 操作运行时类的指定构造器
    /*
    操作运行时类指定构造器
    */
    @Test
    public void getConstructor() throws Exception {
        Class clazz = Person.class;

        //调用运行时类中的指定的构造器,参数:指明参数的构造列表
        Constructor constructor = clazz.getDeclaredConstructor(String.class);
        //保证此构造器可访问
        constructor.setAccessible(true);
        //调用此构造器创建运行时类的对象
        Person person1 = (Person) constructor.newInstance("Tom");
        System.out.println(person1);
    }
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小黑cc

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值