Java反射机制

一、Class类与Java反射

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

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

Class texfFieldC = textField.getClass(); // textField为JTextField类的对象

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

       在通过getFields()和getMethods()方法依次获得权限为public的成员变量和方法时,将包含从超类中继承到的成员变量和方法;而通过方法getDeclaredFields()和getDeclaredMethods()只是获得在本类中定义的所有成员变量和方法。

1、访问构造方法

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

  • getConstructors()。
  • getConstructor(Class<?> "parameterTypes)。
  • getDeclaredConstructorsO。
  • getDeclaredConstructor(Class <?>**parameterTypes)。

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

objectClass.getDeclaredConstructor(String.class, int.class);
objectClass.getDeclaredConstructor(new ClassQ { String.class, int.class );

Constructor类中提供的常用方法下表所示:

       通过java.lang.eflect.Modifier类可以解析出getModifiers()方法的返回值所表示的修饰符信息等。该类常用静态方法如下表所示:

例:

Example_01 .java

public class Example_01 {
	String s;
	int i, i2, i3;
	private Example_01() {
	}
	protected Example_01(String s, int i) {
		this.s = s;
		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("s=" + s);
		System.out.println("i=" + i);
		System.out.println("i2=" + i2);
		System.out.println("i3=" + i3);
	}
}

Main_01.java

import java.lang.reflect.*;

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 j = 0; j < exceptionTypes.length; j++) {
				System.out.println(" " + exceptionTypes[j]);				
			}
			
			Example_01 example2 = null;
			while (example2 == null) {
				// 如果该成员变量的访问权限为private,则抛出异常,即不允许访问
				try {					
					if (i == 2) {
						// 通过执行默认没有参数的构造方法创建对象
						example2 = (Example_01)constructor.newInstance();
					}else if (i == 1) {
						// 通过执行2个参数的构造方法创建对象
						example2 = (Example_01)constructor.newInstance("2", 6);
					}else {
						// 通过执行多个参数的构造方法创建对象
						Object[] parameters = new Object[] {new String[] {"222", "666", "888"}};
						example2 = (Example_01)constructor.newInstance(parameters);
					}
				} catch (Exception e) {
					System.out.println("在创建对象时抛出异常,下面执行setAccessible()方法");
					constructor.setAccessible(true); 		// 设置为允许访问
				}			
			}	
			if (example2 != null) {
				example.print();
				System.out.println();
			}
		}	
	}
}

输出:

// 访问Example_01(String... strings)输出

// 访问Example_01(String s, int i)输出:

// 访问Example_01()输出:

2、访问成员变量

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

  • getFields()。
  • getField(String name)。
  • getDeclaredFields()。
  • getDeclaredField(String name)。

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

object. getDeclaredField("birthday");

Field类中提供的常用方法下表所示:

3、访问方法

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

  • getMethods()。
  • getMethod(String name, Casse?>**parameterTypes)。
  • getDeclaredMethods()。
  • getDeclaredMethod(String name, Class<?>...parameterTypes)。

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

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

Method类中提供的常用方法下表所示:

例:

Example_03.java

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();
	}
}

Main_03.java

import java.lang.reflect.*;

public class Main_03 {
	public static void main(String[] args) {
		Example_03 example = new Example_03();
		Class exampleC = example.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 j = 0; j < exceptionTypes.length; j++) {
				System.out.println(" " + exceptionTypes[j]);
			}
			boolean isTurn = true;
			while (isTurn) {
				// 如果该方法的访问权限为private,则抛出异常,即不允许访问
				try {
					isTurn = false;
					if("staticMethod".equals(method.getName()))
						method.invoke(example); // 执行没有入口参数的方法
					else if("publicMethod".equals(method.getName()))
						System.out.println("返回值为:"
								+ method.invoke(example, 168)); // 执行方法
					else if("protectedMethod".equals(method.getName()))
						System.out.println("返回值为:"
								+ method.invoke(example, "7", 5)); // 执行方法
					else if("privateMethod".equals(method.getName())) {
						Object[] parameters = new Object[] { new String[] {
								"M", "W", "Q" } }; // 定义二维数组
						System.out.println("返回值为:"
								+ method.invoke(example, parameters));
					}
				} catch (Exception e) {
					System.out.println("在执行方法时抛出异常,"
							+ "下面执行setAccessible()方法!");
					method.setAccessible(true); // 设置为允许访问
					isTurn = true;
				}
			}
			System.out.println();
		}
	}
}

输出:

// 访问publicMethod()方法输出:

// 访问privateMethod()方法输出:

// 访问protectedMethod()方法输出:

// 访问staticMethod()方法输出:

 

二、使用Annotation(注释)功能

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

1、定义

       在定义Annotation类型时,也需要用到用来定义接口的interface关键字,但需要在interface关键字前加一-个“@”符号,即定义Annotation类型的关键字为@interface,这个关键字的隐含意思是继承了java.lang anotation.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类型。

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

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

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

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

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

例:

Constructor_Annotation.java

import java.lang.annotation.*;

//用于构造方法
@Target(ElementType.CONSTRUCTOR)

//在运行时加载Annotation到JVM中
@Retention(RetentionPolicy.RUNTIME)

public @interface Constructor_Annotation {
	String value() default "默认构造方法" ;
}

Field_Method_Parameter_Annotation.java

import java.lang.annotation.*;

//用于字段、方法和参数
@Target( {ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER} )

//在运行时加载Annotation到JVM中
@Retention(RetentionPolicy.RUNTIME)

public @interface Field_Method_Parameter_Annotation {
	String describe();					// 定义一个没有默认值的String型成员
	Class type() default void.class;	// 定义一个具有默认值的Class型成员
}

Record.java

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(
		@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 = "设置编号")
	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;
	}
}

Main_05.java

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

public class Main_05 {
	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("-------- 字段的描述如下 --------");
		// 获得所有字段
		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();
		}
	}
}

输出:

 

小结:

       利用Java反射机制,可在程序运行时访问类的所有描述信息(经常需要访问的有类的构造方法、成员变量和方法),实现逆向控制程序的执行过程。利用Annotation功能,可对类、构造方法、成员变量、方法、参数等进行注释,在程序运行时通过反射可读取这些信息,根据读取的信息逆向控制程序的执行过程。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值