Java第十六章反射与注解

反射

 

通过 Java 反射机制,可以在程序中访问已经装到JVM 中的 Java 对象的描述现访同、检测和修改描述Java 对象本身信息的功能。

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

JTextFieid textField = new JTextField0;        //创建JTextField 对象

Class textFieldC = textField.getClass();        //获取 Class 对象

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

 

访问构造方法

在通过下列一组方法访问构造方法时,将返回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 类可以解析出 getModifiers0方法的返回值所表示的修饰符信息,在该类中提供了一系列用来解析的静态方法,既能查看是否被指定的修饰符修饰,又能以字符串的形式获得所有修饰符。Modifier 类常用静态方法如所示。

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

int modifiers = constructor.getModifiers();

boolean isEmbellishByPrivate = Modifier.isPrivate(modifiers);

String embellishment = Modifier.toString(modifiers);

 代码案例:

package com.mr;
 
public class Demo1 {
	String s;
	int i, i2, i3;
	private Demo1() {
	}
	protected Demo1(String s, int i) {
		this.s = s;
		this.i= i;
	}
	public Demo1(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);
	}
}

 然后编写测试类ConstructorDemo1,在该类中通过反射访问com.mr.Demo1类中的所有构造方法并将该构造方法是否允许带有可变数量的参数、入口参数类型和可能抛出的异常类型信息输出到控台。具体代码如下:

package com.mr;
 
import java.lang.reflect.Constructor;
 
public class ConstructorDemo1 {
	public static void main(String[] args) {
		Demo1 d1 = new Demo1("10","20","30");
		Class<? extends Demo1> Demo1Class = d1.getClass();
		//获得所有构造方法
		Constructor[] declaredConstructors = Demo1Class.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]);
			}
			Demo1 d2 = null;
			while (d2 == null) {
				try{	//如果构造方法的访问权限为 private或 protected,则抛出异常,即不允许
					if(i ==2)	//通过执行默认没有参数的方法创建对象
						d2 =(Demo1) constructor.newInstance();
					else if (i == 1)
						//通过执行具有两个参数的构造方法创建对象
						d2 =(Demo1)constructor.newInstance("7", 5);
					else{//通过执行具有可变数量参数的构造方法创建对象
						Object[] parameters = new Object[] { new String[] { "100","200","300" }};
						d2 =(Demo1) constructor.newInstance(parameters);
					}
				}catch (Exception e) {
					System.out.println("在创建对象时抛出异常,下面执行 setAccessible()方法");
					constructor.setAccessible(true);	//设置为允许访问
				}
			}
			if (d2 != null) {
				d2.print();
				System.out.println();
			}
		}
	}
 
}

 运行结果如下:

当反射无参构造方法时将输出所有属性的默认值,当反射有参数的构造方法时将输方法参数赋予的相应值。

 访问成员变量

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

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

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

object. getDeclaredField("birthday");

 Field类中提供的常用方法如表 16.4 所示。

  代码案例:

然后通过反射访问com.mrDemo2类中的所有成员变量将成员变量的名称和类型信息输出到控制

台,并分别将各个成员变量在修改前后的值输出到控制台。关键代码如下:

package com.mr;
 
import java.lang.reflect.Field;
 
public class Demo2 {
	public static void main(String[] args) {
		F example =new F();
		Class exampleC = example.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 或 protected,则抛出异常,即不允许访问
				try {
					isTurn = false;
					//获得成员变量值
					System.out.println("修改前的值为:"+ field.get(example));
					if (fieldType.equals(int.class)) {	//判断成员变量的类型是否为 int型
						System.out.println("利用方法 setlnt()修改成员变量的值");
						field.setInt(example,168);//为 int 型成员变量赋值
					}else if (fieldType.equals(float.class)){	//判断成员变量的类型是否为 float型
						System.out.println("利用方法 setFloat()修改成员变量的值");
						field.setFloat(example, 99.9F);//为 float 型成员变量赋值
					}else if (fieldType.equals(boolean.class)){//判断成员变量的类型是否为 boolean型
						System.out.println("利用方法 setBoolean()修改成员变量的值");
						field.setBoolean(example, true);//为 boolean 型成员变量赋值
					}else {
						System.out.println("利用方法 set()修改成员变量的值");
						field.set(example,"MWQ");//可以为各种类型的成员变量赋值
					}
					//获得成员变量值
					System.out.println("修改后的值为:"+ field.get(example));
				} catch (Exception e) {
					System.out.println("在设置成员变量值时抛出异常,"+"下面执行 setAccessible()方法!");
					field.setAccessible(true);//设置为允许访问
					isTurn = true;
				}
			}
			System.out.println();
		}
	}
}
		
	
 
 

 运行结构如下:

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

访问成员方法

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

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

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

objectClass.getDeclaredMethod("print",String.class, int.class);

objectClass.getDeclaredMethod("print", new Class (String.class, int.class ));

 Method 类中提供的常用方法如表所示。

package com.mr;
 
public class D {
	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();
		
	}
 
}

 然后通过反射访问 com.mr.Demo3 类中的所有方法,将各个方法的名称、入口参数类型、返回值类型等信息输出到控制台,并执行部分方法。关键代码如下:

package com.mr;
 
import java.lang.reflect.Method;
 
public class Demo3 {
	public static void main(String[] args) {
		D demo = new D();
		Class demoClass = demo.getClass();
		Method[] declaredMethods = demoClass.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) {
				try {	//如果该方法的访问权限为 private 或 protected,则抛出异常,即不允许访问
					isTurn = false;
					if ("staticMethod".equals(method.getName()))
						method.invoke(demo); //执行没有入口参数的方法
					else if("publicMethod".equals(method.getName()))
						System.out.println("返回值为:"+method.invoke(demo,168)) ;//执行方法
					else if ("protectedMethod".equals(method.getName()))
						System.out.println("返回值为:"+method.invoke(demo,"7",5));//执行方法
					else if ("privateMethod".equals(method.getName())){//定义二维数组
					 Object[] parameters = new Object[]{ new String[] {"M","w","Q" }};
					 System.out.println("返回值为:"+ method.invoke(demo,parameters));
				}
			}catch(Exception e){
				System.out.println("在执行方法时抛出异常,"+"下面执行setAccessible()方法!");
				method.setAccessible(true);//设置为允许访问
				isTurn = true;
			}
		}
		System.out.println();
		}
	}
}
 
 

 运行结果如下:

 

 定义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() default"<默认值>”;

        Class type() default void.class;

}

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

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

代码案例:

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

 访问Annotation 信息

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

Constructor 类、Field 类和 Method 类均继承了AccessibleObjiect 类,在AccessibleObject 中定义了3个关于Annotation 的方法。其中,方法isAnnotationPresent(Class<?extends Annotation> annotationClass用来查看是否添加了指定类型的 Annotation,如果是则返回 rue,否则返回 false; 方法getAnnotatiot(Class<T>annotationClass)用来获得指定类型的Annotation,如果存在则返回相应的对象,否则返回nul方法getAnnotations()用来获得所有的Annotation,该方法将返回一个Annotation数组。

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值