Java反射机制

本文围绕Java展开,介绍了Class类与Java反射机制,可在程序中访问、检测、修改Java对象信息,还说明了访问构造方法、成员变量和方法的方式。同时阐述了Java的Annotation功能,包括定义Annotation类型及访问其相关信息的方法。

一、Class 类与 Java 反射

1、什么是反射

通过 Java 反射机制,可以在程序中访问已经装载到 JVM 中的 Java 对象的描述,实现访问、检测、修改描述 Java 对象本身信息的功能。
java.lang.reflect 包中提供了该功能。

所有的 Java 类继承 Object 类,在 Object 类中定义了一个 getClass() 方法,该方法返回一个类型为 Class 的对象。
例如,创建了一个 Example_01 的实体类,获取 Example_01 类的对象:

Example_01 example01 = new Example_01();
Class testFieldC = example01.getClass(); 	// example01 为 Example_01 类的对象

通过反射可访问的主要描述信息:

在这里插入图片描述
注意: getFields()getMethods() 方法依次获得权限为 public 的成员变量和方法时,将包含从超类中继承到的成员变量和方法;而 getDeclaredFields()getDeclaredMethods() 只是获得本类中定义的所有成员变量和方法。

2、访问构造方法

通过下列方法访问构造方法时,将返回 Constructor 类型的对象或数组。每个 Constructor 对象代表一个构造方法,利用 Constructor 对象可以操纵相应的构造方法。

  1. getConstructors()
  2. getConstructor(Class<?>… parameterTypes)
  3. getDeclaredConstructors()
  4. getDeclaredConstructor(Class<?>… parameterTypes)

如果想要访问指定的构造方法,需要根据该构造方法的入口参数类型访问。比如,入口参数类型依次为 String 和 int,访问方式有如下两种:

objectClass.getDeclaredConstructor(String.class,int.class);
objectClass.getDeclaredConstructor(new Class[]{String.class,int.class});

在这里插入图片描述
通过 java.lang.reflect.Modifier 类可以解析出 getModifiers() 方法的返回值所表示的修饰符信息,可以查看是否被指定的修饰符修饰,还可以以字符串的形式获得所有修饰符。

在这里插入图片描述
在这里插入图片描述

访问构造方法实例

实体类:

package com.reflect;

/**
 *  创建 Example_01 类
 *  类中声明一个 String 成员变量和3个 int 类型成员变量
 *  提供 3 个构造方法
 */
public class Example_01 {

    String str;

    int i, i2, i3;

    private Example_01() {

    }

    protected Example_01(String str, int i) {
        this.str = str;
        this.i = i;
    }

    public Example_01(String... strings) throws NumberFormatException {

        if (0 < strings.length)
            i = Integer.valueOf(strings[0]);
        if (1 < strings.length)
            i2 = Integer.valueOf(strings[1]);
        if (2 < strings.length)
            i3 = Integer.valueOf(strings[2]);

    }

    public void print() {
        System.out.println("str = " + str);
        System.out.println("i = " + i);
        System.out.println("i2 = " + i2);
        System.out.println("i3 = " + i3);
    }
}

测试类:

package com.reflect;

import java.lang.reflect.Constructor;

/**
 * 创建测试类 Main_01
 * 通过反射访问 Example_01 类
 */
public class Main_01 {

    public static void main(String[] args) {

        Example_01 example = new Example_01("10", "20", "30");

        Class<? extends Example_01> exampleC = example.getClass();

        // 获得所有构造方法
        Constructor[] declaredConstructors = exampleC.getDeclaredConstructors();

        for (int i = 0; i < declaredConstructors.length; i++) {         // 遍历构造方法

            Constructor<?> constructor = declaredConstructors[i];
            System.out.println("查看是否带有可变数量的参数:" + constructor.isVarArgs());
            System.out.println("该构造方法的入口参数类型依次为:");
            Class[] parameterTypes = constructor.getParameterTypes();   // 获取所有参数类型
            for (int j = 0; j < parameterTypes.length; j++) {
                System.out.println(" " + parameterTypes[j]);
            }
            System.out.println("该构造方法可能抛出的异常类型为:");

            //  获得所有可能抛出的异常信息类型
            Class[] exceptionTypes = constructor.getExceptionTypes();

            for (int k = 0; k < exceptionTypes.length; k++) {
                System.out.println(" " + exceptionTypes[k]);
            }

            Example_01 example2 = null;

            while (example2 == null) {
                try {   //  如果该成员变量的访问权限为private,则抛出异常,即不允许访问
                    if (i == 2)     //  通过执行默认的没有参数的构造方法创建对象
                        example2 = (Example_01) constructor.newInstance();
                    else if (i == 1)
//                        通过执行具有两个参数的构造方法创建对象
                        example2 = (Example_01) constructor.newInstance("7", 5);
                    else {
//                        通过执行具有可变数量参数的构造方法创建对象
                        Object[] parameters = new Object[]{new String[]{"100", "200", "300"}};
                        example2 = (Example_01) constructor.newInstance(parameters);
                    }

                } catch (Exception e) {
                    System.out.println("在创建对象时抛出异常,下面执行setAccessible()方法");
                    constructor.setAccessible(true);    //  设置为允许访问

                }

            }
            if (example2 != null) {
                example2.print();
                System.out.println();
            }
        }
    }
}

打印结果:

查看是否带有可变数量的参数:true
该构造方法的入口参数类型依次为:
 class [Ljava.lang.String;
该构造方法可能抛出的异常类型为:
 class java.lang.NumberFormatException
str = null
i = 100
i2 = 200
i3 = 300

查看是否带有可变数量的参数:false
该构造方法的入口参数类型依次为:
 class java.lang.String
 int
该构造方法可能抛出的异常类型为:
str = 7
i = 5
i2 = 0
i3 = 0

查看是否带有可变数量的参数:false
该构造方法的入口参数类型依次为:
该构造方法可能抛出的异常类型为:
在创建对象时抛出异常,下面执行setAccessible()方法
str = null
i = 0
i2 = 0
i3 = 0


Process finished with exit code 0

3、访问成员变量

下列方法将返回 Field 类型的对象或数组。每个 Field 对象代表一个成员变量,利用 Field 对象可以操纵相应的成员变量。

  1. getFields()
  2. getField(String name)
  3. getDeclaredField(String name)
  4. getDeclaredFields()

如果要访问特定的成员变量,可以通过成员变量的名字访问。比如:访问名称是 age 的成员变量,方法如下:

object.getDeclaredField("age")

Field 类常用的方法

在这里插入图片描述

访问成员变量实例

实体类:

/**
 * 创建 Example_02
 * 声明 int, float, boolean, String 型成员变量
 */
public class Example_02 {

    int i;
    public float f;
    protected boolean b;
    private String s;

}

测试类:

package com.reflect;

import java.lang.reflect.Field;

public class Main_02 {

    public static void main(String[] args) {

        Example_02 example_02 = new Example_02();

        Class exampleC = example_02.getClass();

        // 获取所有的成员变量
        Field[] declaredFields = exampleC.getDeclaredFields();

        for (int i = 0; i < declaredFields.length; i++) { // 遍历所有的成员变量

            Field field = declaredFields[i];
            System.out.println("成员变量的名称是:" + field.getName());        //  获得成员变量的名称
            Class fieldType = field.getType(); // 获得成员变量类型
            System.out.println("成员变量的类型是:" + fieldType);

            boolean isTurn = true;

            while (isTurn) {

                // 如果该成员变量的访问权限是 private,则抛出异常,即不允许访问
                try {

                    isTurn = false;

                    // 获得成员变量的值
                    System.out.println("修改前的值是:" + field.get(example_02));

                    // 判断成语变量的类型是否 int 类型
                    if (fieldType.equals(int.class)) {

                        System.out.println("利用方法 setInt() 修改成员变量的值");
                        field.setInt(example_02, 168);

                        // 判断成语变量的类型是否 float 类型
                    } else if (fieldType.equals(float.class)) {

                        System.out.println("利用方法 setFloat() 修改成员变量的值");
                        field.setFloat(example_02, 99.9F);

                        // 判断成语变量的类型是否 boolean 类型
                    } else if (fieldType.equals(boolean.class)) {

                        System.out.println("利用方法 setBoolean() 修改成员变量的值");
                        field.setBoolean(example_02, true);

                    } else {

                        System.out.println("利用方法 set() 修改成员变量的值");
                        field.set(example_02, "MWV");

                    }

                    // 获得成员变量的值
                    System.out.println("修改后的值为:" + field.get(example_02));

                } catch (Exception e) {

                    System.out.println("在设置成员变量值时抛出异常,下面执行 setAccessible()方法!");
                    field.setAccessible(true); // 设置为允许访问
                    isTurn = true;

                }

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

打印结果:

成员变量的名称是:i
成员变量的类型是:int
修改前的值是:0
利用方法 setInt() 修改成员变量的值
修改后的值为:168

成员变量的名称是:f
成员变量的类型是:float
修改前的值是:0.0
利用方法 setFloat() 修改成员变量的值
修改后的值为:99.9

成员变量的名称是:b
成员变量的类型是:boolean
修改前的值是:false
利用方法 setBoolean() 修改成员变量的值
修改后的值为:true

成员变量的名称是:s
成员变量的类型是:class java.lang.String
在设置成员变量值时抛出异常,下面执行 setAccessible()方法!
修改前的值是:null
利用方法 set() 修改成员变量的值
修改后的值为:MWV


Process finished with exit code 0

4、访问方法

下列方法将返回 Method 类型的对象或数组。每个 Method 对象代表一个方法,利用 Method 对象可以操纵相应的方法。

  1. getMethods()
  2. getMethod(String name, Class<?>… parameterTypes)
  3. getDeclaredMethods()
  4. getDeclaredMethod(String name, Class<?>… parameterTypes)

如果访问特定的方法,需要方法名称参数类型。比如:方法名:print,入口参数:String、int 型。通过下面两种方式可以访问:

objectClass.getDeclaredMethod("print",String.class,int.class);
objectClass.getDeclaredMethod("print",new Class[]{String.class,int.class});

Method 类提供的常用方法:

在这里插入图片描述

访问方法实例

实体类:

package com.reflect;

public class Example_03 {


    static void staticMethod() {
        System.out.println("执行 staticMethod() 方法");
    }

    public int publicMethod(int i) {

        System.out.println("执行 publicMethod() 方法");
        return i * 100;

    }

    protected int protectedMethod(String s, int i) throws NumberFormatException {

        System.out.println("执行 protectedMethod() 方法");
        return Integer.valueOf(s) + i;

    }

    private String privateMethod(String... strings) {

        System.out.println("执行 privateMethod() 方法");
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < strings.length; i++) {
            stringBuffer.append(strings[i]);
        }
        return stringBuffer.toString();
    }
}

测试类:

package com.reflect;

import java.lang.reflect.Method;

public class Main_03 {

    public static void main(String[] args) {

        Example_03 example_03 = new Example_03();

        Class exampleC = example_03.getClass();

        Method[] declaredMethods = exampleC.getDeclaredMethods();

        for (int i = 0; i < declaredMethods.length; i++) {      // 遍历方法

            Method method = declaredMethods[i];
            System.out.println("方法名是:" + method.getName());    // 方法名
            System.out.println("是否带有可变参数:" + method.isVarArgs());
            System.out.println("入口的参数类型依次是:");

            Class[] parameterTypes = method.getParameterTypes();  // 获得所有参数类型

            for (int j = 0; j < parameterTypes.length; j++) {

                System.out.println(" " + parameterTypes[j]);

            }

            System.out.println("方法返回值类型是:" + method.getReturnType()); // 获得方法返回值类型
            System.out.println("可能抛出的异常类型是:");

            Class[] exceptionTypes = method.getExceptionTypes(); // 获得所有异常类型
            for (int k = 0; k < exceptionTypes.length; k++) {
                System.out.println(" " + exceptionTypes[k]);
            }

            boolean isTurn = true;

            while (isTurn) {

                // 如果该方法的访问权限是 private,抛出异常,即不允许访问
                try {

                    isTurn = false;

                    if ("staticMethod".equals(method.getName())) {

                        method.invoke(example_03); // 执行美哦与入口参数的方法

                    } else if ("publicMethod".equals(method.getName())) {

                        System.out.println("返回值为:" + method.invoke(example_03, 168)); // 执行方法

                    } else if ("protectedMethod".equals(method.getName())) {

                        System.out.println("返回值是:" + method.invoke(example_03, "7", 5)); // 执行方法

                    } else if ("privateMethod".equals(method.getName())) {

                        Object[] params = new Object[]{new String[]{"H", "J", "F"}};  // 定义二维数组
                        System.out.println("返回值是:" + method.invoke(example_03, params));
                    }

                } catch (Exception e) {

                    System.out.println("在执行方法时抛出异常,下面执行 setAccessible()方法!");
                    method.setAccessible(true); // 设置为允许访问
                    isTurn = true;


                }
            }
        }
    }
}

打印结果:

方法名是:protectedMethod
是否带有可变参数:false
入口的参数类型依次是:
 class java.lang.String
 int
方法返回值类型是:int
可能抛出的异常类型是:
 class java.lang.NumberFormatException
执行 protectedMethod() 方法
返回值是:12
方法名是:staticMethod
是否带有可变参数:false
入口的参数类型依次是:
方法返回值类型是:void
可能抛出的异常类型是:
执行 staticMethod() 方法
方法名是:publicMethod
是否带有可变参数:false
入口的参数类型依次是:
 int
方法返回值类型是:int
可能抛出的异常类型是:
执行 publicMethod() 方法
返回值为:16800
方法名是:privateMethod
是否带有可变参数:true
入口的参数类型依次是:
 class [Ljava.lang.String;
方法返回值类型是:class java.lang.String
可能抛出的异常类型是:
在执行方法时抛出异常,下面执行 setAccessible()方法!
执行 privateMethod() 方法
返回值是:HJF

Process finished with exit code 0

注意:在反射中执行具有可变参数的构造方法,需要将入口参数定义成二维数组。

二、使用 Annotation 功能

Java提供了 Annotation 功能,可用于类、构造方法、成员变量、反复噶、参数等声明中。

1、定义 Annotation 类型

定义 Annotation 类型 需要关键字 @interface 关键字。这个关键字的隐含意思是继承了java.lang.annotation.Annotation

示例代码如下:

public @interface NoMemberAnnotation {
}

上面的 Annotation 类型 @NoMemberAnnotation 未包含任何成员,这样的类型被称作 maker annotation

下面代码定义包含一个成员:

public @interface OneMemberAnnotation {
    
    String value();
}
  • String: 成员类型。可用的类型有:String、primitive、enumerated 和 annotation,以及所列类型的数组。
  • value:成员名称。如果只包含一个成员,通常命名为 value。

下面代码包含多个成员:

public @interface MoreMemberAnnotation {

    String describe();

    Class type();
}

在定义 Annotation 类型时,也可以为成员设置默认值。如下:

public @interface MoreMemberAnnotation {

    String describe() default "默认值";

    Class type() default void.class;
}

在定义 Annotation 类型,可以通过 @Target 设置 Annotation 用在什么位置。如果未设置,表示适用任何地方。枚举类 ElementType 中的枚举常量用来设置 @Target。

在这里插入图片描述
@Retention 可以设置 Annotation 的有效范围,通过枚举类 RetentionPolicy 设置。如果未设置 @Retention,有效范围是枚举常量 CLASS 表示的范围。

在这里插入图片描述

定义 Annotation 示例

Annotation 1:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.CONSTRUCTOR)    // 用于构造方法
@Retention(RetentionPolicy.RUNTIME) // 运行时加载 Annotation 到 JVM 中
public @interface Constructor_Annotation {

    String value() default "默认构造方法"; // 定义一个具有默认值的 String 成员
}

Annotation 2:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.FIELD,ElementType.METHOD,ElementType.PARAMETER}) // 用于字段、方法、参数
@Retention(RetentionPolicy.RUNTIME)
public @interface Field_Method_Parameter_Annotation {

    String describe();
    Class type() default void.class;
}

创建 Record 类使用:

public class Record {

    @Field_Method_Parameter_Annotation(describe = "编号", type = int.class)
    int id;

    @Field_Method_Parameter_Annotation(describe = "姓名", type = String.class)
    String name;

    @Constructor_Annotation
    public Record() {
    }

    @Constructor_Annotation(value = "立即初始化构造方法")
    public Record(
            @Field_Method_Parameter_Annotation(describe = "编号参数", type = int.class) int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Field_Method_Parameter_Annotation(describe = "获得编号", type = int.class)
    public int getId() {
        return id;
    }

    @Field_Method_Parameter_Annotation(describe = "设置编号", type = int.class)
    public void setId(int id) {
        this.id = id;
    }
    
}

2、访问 Annotation 信息

如果 @Retention 设置为 RetentionPolicy.RUNTIME,那么在运行时可以通过反射获得 Annotation 相关信息。

Constructor、Method、Field 都继承了 AccessibleObject 类。AccessibleObject 类定义了3个关于 Annotation 方法:

  1. isAnnotationPresent(Class<? extends Annotation> annotationClass):查看是否添加指定类型的 Annotation
  2. getAnnotation(Class annotationClass):用来获得指定类型的 Annotation
  3. getAnnotations():获得所有的 Annotation

在类 Constructor 和 Method 中还定义了方法 getParameterAnnotations(),用来获得为所有参数添加的 Annotation,将以 Annotation 类型的二维数组返回,在数组中的顺序与声明的顺序相同,如果没有参数则返回一个长度为0的数组;如果存在未添加 Annotation 的参数,将用一个长度为0嵌套数组占位。

以下为代码示例,实体类继续使用上面的 Record 实体类。

(1)访问构造方法及其包含参数的 Annotation 信息

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

public class Annotation_Constructor_Main {

    public static void main(String[] args) {

        Record record = new Record();

        Class recordC = record.getClass();

        Constructor[] declaredConstructors = recordC.getDeclaredConstructors(); // 获得所有构造方法

        // 查看是否具有指定类型的注释
        for (int i = 0; i < declaredConstructors.length; i++) {

            Constructor constructor = declaredConstructors[i];

            if (constructor.isAnnotationPresent(Constructor_Annotation.class)) {

                Constructor_Annotation ca = (Constructor_Annotation) constructor.getAnnotation(Constructor_Annotation.class);
                System.out.println(ca.value()); // 获得注释信息

            }

            Annotation[][] parameterAnnotations = constructor.getParameterAnnotations();

            for (int j = 0; j < parameterAnnotations.length; j++) {

                // 获取指定参数注释的长度
                int length = parameterAnnotations[j].length;
                if (length == 0) { // 如果长度是0,表示没有给参数添加注释
                    System.out.println("未添加 Annotation 的参数");
                } else {
                    for (int k = 0; k < length; k++) {
                        // 获得参数注释
                        Field_Method_Parameter_Annotation pa = (Field_Method_Parameter_Annotation) parameterAnnotations[j][k];
                        System.out.println(" " + pa.describe()); // 获得参数描述
                        System.out.println(" " + pa.type()); // 获得参数类型

                    }
                }
            }
        }
    }
}

打印信息:

默认构造方法
立即初始化构造方法
 编号参数
 int
未添加 Annotation 的参数

Process finished with exit code 0

(2)访问字段的 Annotation 信息

import java.lang.reflect.Field;

public class Annotation_Field_Main {

    public static void main(String[] args) {

        Record record = new Record();

        Class recordC = record.getClass();

        Field[] declaredFields = recordC.getDeclaredFields(); // 获得所有字段

        for (int i = 0; i < declaredFields.length; i++) {

            Field field = declaredFields[i];

            // 查看是否具有指定类型的注释
            if (field.isAnnotationPresent(Field_Method_Parameter_Annotation.class)) {

                Field_Method_Parameter_Annotation fa = field.getAnnotation(Field_Method_Parameter_Annotation.class);
                System.out.println("  " + fa.describe());
                System.out.println("  " + fa.type());

            }
        }
    }
}

打印信息:

  编号
  int
  姓名
  class java.lang.String

Process finished with exit code 0

(3)访问方法及其包含参数的 Annotation 信息

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

public class Annotation_Method_Main {


    public static void main(String[] args) {
        Record record = new Record();

        Class recordC = record.getClass();

        Method[] methods = recordC.getDeclaredMethods(); // 获得所有方法

        for (int i = 0; i < methods.length; i++) {

            Method method = methods[i];

            if (method.isAnnotationPresent(Field_Method_Parameter_Annotation.class)) {

                Field_Method_Parameter_Annotation ma = method.getAnnotation(Field_Method_Parameter_Annotation.class);
                System.out.println(" " + ma.describe());
                System.out.println(" " + ma.type());

            }

            Annotation[][] parameterAnnotations = method.getParameterAnnotations();

            for (int j = 0; j < parameterAnnotations.length; j++) {

                int length = parameterAnnotations[j].length;

                if (length == 0) {
                    System.out.println(" 未添加 Annotation 参数");
                } else {
                    for (int k = 0; k < length; k++) {

                        Field_Method_Parameter_Annotation pa = (Field_Method_Parameter_Annotation) parameterAnnotations[j][k];
                        System.out.println(" " + pa.describe());
                        System.out.println(" " + pa.type());

                    }
                }
            }
        }
    }
}

打印信息:

 获得编号
 int
 未添加 Annotation 参数
 设置编号
 int
 未添加 Annotation 参数

Process finished with exit code 0
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

YD_1989

分享不易,非常感谢您的鼓励支持

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

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

打赏作者

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

抵扣说明:

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

余额充值