Java第十六章反射与注解

一、反射

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

众所周知,所有Java类均继承Object类,在Object类中定义了一个getClass()方法,该方法返回一个类型为Class的对象。例如下面的代码:

利用Class类的对象textFieldC,可以访问用来返回该对象的textField对象的描述信息。可以访问的主要描述信息如下表

1、访问构造方法

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

getConstructors()。

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

getDeclaredConstructors()。

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

如果是访问指定的构造方法,需要根据该构造方法的入口参数的类型来访问。例如,访问一个入口参数类型依次为String型和int型的构造方法,通过下面两种方法均可实现:

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

Constructor类中提供的常用方法如下表。

通过Java.lang.reflect.Modifier类可以解析出getModifiers()方法的返回值所表示的修饰符信息,在该类中提供了一系列用来解析的静态方法,既能查看是否被指定的修饰符修饰,又能以字符串的形式获得所有修饰符。Modifier类常用静态方法如下表。

例如,判断对象Constructor所代表的构造方法是否被private修饰,以及以字符串形式获得该构造方法的所有修饰符的典型代码如下:

int modifiers = constructor.getModifiers();
boolean isEmbellishByPrivate = Modifier.isPrivate(modifiers);
String embellishment = Modifier.toString(modifiers);

例题:反射一个类的所有构造方法

在com.mr包下创建一个Demo2类,在该类中声明一个String型成员变量和3个int型成员变量,并提供3个构造方法。具体代码如下:

运行结果:

2、访问成员变量

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

getFields()。

getField(String name)。

getDeclaredFields()。

getDeclaredField(String name)。

如果是访问指定的成员变量,可以通过该成员变量的名称来访问。例如,访问一个名称为birthday的成员变量,访问方法如下:

object.getDeclaredField("birthday");

Field类中提供的常用方法如下:

例题:反射一个类的所有成员变量

在com.mr包下创建一个Demo3类,在该类中依次声明一个int、float、Boolean和String型的成员变量,并将它们设置为不同的访问权限。

运行结果:

通过这个结果可以看出,在反射权限为private和protected的成员变量时,需要执行SetAccessible()方法,并将入口参数设为true,否则不允许访问。

3、访问成员方法

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

getMethods()。

getMethod(String name ,Class<?>...parameterTypes)。

getDeclaredMethods()。

getDeclaredMethods(String name,Class<?>...parameterTypes)。

如果是访问指定的方法,需要根据该方法的名称和入口参数的类型来访问。例如,访问一个名称为print、入口参数类型依次为String型和int型的方法,通过下面两种方式均可实现:

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

Method类中提供的常用方法如下表

例题:反射一个类的所有成员方法

在com.mr包下创建一个Demo4类,并编写4个成员方法。具体如下:

运行结果:

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

课堂代码:

二、Annotation注释功能

Java中提供了Annotation注释功能,该功能可用于类、构造方法、成员变量、参数等的声明中。该功能并不影响程序的运行,但是会对编译器警告等辅助工具产生影响。

1、定义Annotation注释功能

在定义Annotation类型时,也需要用到来定义接口的interface关键字,但需要在interface关键字前加一个“@”符号,既定义Annotation类型的关键字为@interface,这个关键字的隐含意识是继承了java.lang.annotation.Annotation接口。例如,下面的代码就定义了一个Annotation类型:

public @interface NoMemberAnnotation{
}

上面定义的Annotation类型@NoMemberAnnotation未包含任何成员,这样的Annotation类型被称为marker annotation。下面的代码定义了一个只包含一个成员的Annotation类型:

public @interface OneMemberAnnotation{
    String value();
}

String:成员类型。可用的成员类型有String、Class、primitive、enumerated和annotation,以及所列类型的数组。

value:成员名称。如果在定义所定义的Annotation类型中只包含一个成员,通常将成员名称命名为value。

下面的代码定义了一个包含多个成员的Annotation类型:

public @interface MoreMemberAnnotation{
    String describe();
    Class type();
}

在为Annotation类型定义成员时,也可以为成员设置默认值。例如,下面的代码在定义Annotation类型时就为成员设置了默认值:

public @interface DefaultValueAnnotation{
    String describe() degault"<默认值>";
    Class type() default void.class;
}

在定义Annotation类型时,还可以通过Annotation类型@Target来设置Annotation类型适用的程序元素种类。如果未设置@Target,则表示适用所有程序元素。枚举类ElementType中的枚举常量用来设置@Targer,如下表:

通过Annotation类型@Retention可以设置Annotation的有效范围。枚举类RetentionPolicy中的枚举常量用来设置@Retention,如下表。如果设置@Retention,Annotation的有效范围为枚举常量CLASS表示的范围。

例题:创建自定义的注解

首先定义一个用来注释构造方法的Annotation类型@Constructor_Annotation,有效范围为在运行时加载Annotation到JVM中。完整代码如下:

import java.lang.annotation.*;

@Target(ElementType.CONSTRUCTOR)
// 用于构造方法
@Retention(RetentionPolicy.RUNTIME)
// 在运行时加载Annotation到JVM中
public @interface Constructor_Annotation {
	String value() default "默认构造方法"; // 定义一个具有默认值的String型成员
}

然后定义一个用来注释字段、方法和参数的Annotation类型@Field_Method_Parameter_Annotation,有效范围为在运行时加载Annotation到JVM中。完整代码如下:

import java.lang.annotation.*;

// 用于字段、方法和参数
@Target( { ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
// 在运行时加载Annotation到JVM中
public @interface Field_Method_Parameter_Annotation {
	String describe(); // 定义一个没有默认值的String型成员
	
	Class type() default void.class; // 定义一个具有默认值的Class型成员
}

最后编写一个Record类,在该类中运用前面定义的Annotation类型@Constructor_Annotation=和@Field_Method_Parmeter_Annotation对构造方法、字段、方法和参数进行注释。完整代码如下:

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("立即初始化构造方法")
	// 注释构造方法
	public Record(@Field_Method_Parameter_Annotation(describe = "编号", type = int.class) int id,
			@Field_Method_Parameter_Annotation(describe = "姓名", type = String.class) 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采用默认值注释方法
	public void setId(
			// 注释方法的参数
			@Field_Method_Parameter_Annotation(describe = "编号", type = int.class) int id) {
		this.id = id;
	}

	@Field_Method_Parameter_Annotation(describe = "获得姓名", type = String.class)
	public String getName() {
		return name;
	}

	@Field_Method_Parameter_Annotation(describe = "设置姓名")
	public void setName(@Field_Method_Parameter_Annotation(describe = "姓名", type = String.class) String name) {
		this.name = name;
	}
}

2、访问Annotaiton信息

如果在定义Annotaiton类型时将@Retention设置为RetentionPolicy.RUNTIME,那么在运行程序时通过反射就可以获取到相关的Annotaiton信息,如获取构造方法、字段和方法的Annotaiton信息。

Constructor类、Field类和Method类均继承了AccessibleObject类,在AccessibleObject类中定义了三个关于Annotaiton的方法。其中,方法isAnnotaitonPresent(Class<? extends Annotaiton>annotaitonClass)用来查看是否添加了指定类型的Annotaiton,如果是则返回true,否则返回false;方法getAnnotaiton(Class<T>annotaitonClass)用来获得指定类型的Annotaiton,如果存在则返回相应的对象,否则返回null;方法getAnnotaiton()用来获得所有Annotaiton,该方法将返回一个Annotaiton数组。

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

例题:访问注释中的信息

首先编写访问构造方法及其包含参数的Annotaiton信息的代码。关键代码如下:

import java.lang.annotation.*;
import java.lang.reflect.*;

public class AnnotationTest {

	public static void main(String[] args) {
		Class recordC = null;
		try {
			recordC = Class.forName("Record");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}

		System.out.println("------ 构造方法的描述如下 ------");
		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.print("    " + pa.describe()); // 获得参数描述
						System.out.println("    " + pa.type()); // 获得参数类型
					}
			}
			System.out.println();
		}

		System.out.println();

		System.out.println("-------- 字段的描述如下 --------");

		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.print("    " + fa.describe()); // 获得字段的描述
				System.out.println("    " + fa.type()); // 获得字段的类型
			}
		}

		System.out.println();

		System.out.println("-------- 方法的描述如下 --------");

		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) // 如果长度为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.print("    " + pa.describe()); // 获得参数的描述
						System.out.println("    " + pa.type()); // 获得参数的类型
					}
			}
			System.out.println();
		}
	}
}
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("立即初始化构造方法")
	// 注释构造方法
	public Record(@Field_Method_Parameter_Annotation(describe = "编号", type = int.class) int id,
			@Field_Method_Parameter_Annotation(describe = "姓名", type = String.class) 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采用默认值注释方法
	public void setId(
			// 注释方法的参数
			@Field_Method_Parameter_Annotation(describe = "编号", type = int.class) int id) {
		this.id = id;
	}

	@Field_Method_Parameter_Annotation(describe = "获得姓名", type = String.class)
	public String getName() {
		return name;
	}

	@Field_Method_Parameter_Annotation(describe = "设置姓名")
	public void setName(@Field_Method_Parameter_Annotation(describe = "姓名", type = String.class) String name) {
		this.name = name;
	}
}

课堂内容:

三、内置注解

@Override介绍:只能用在构造方法和成员变量上,表示修饰一个方法。

@SuppressWarnings作用:抑制编译器警告 作用范围类、成员属性、成员方法

@Deprecated作用:标识已过时 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Violet Evegarden

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

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

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

打赏作者

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

抵扣说明:

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

余额充值