第十六章 反射与注解

16.1 反射:

  1. class类
  2. 获取构造方法
  3. 获取成员属性
  4. 获取成员方法

注解

1.内置注解

2.反射注解

创建Class对象的三种方式

1.使用getClass()方法

object str = new object();

class c = str.getClass()

    Demo1 d1 = new Demo1();
        Class c1 = d1.getClass();

2.使用.class属性

class c = object.class

Class c2 = Demo1.class;

3.使用class类的forname方法

class c = class.forname("全路径"

   Class c3 = Class.forName("com.mr.Demo1");

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

的主要描述信息如表 16.1所示。

16.1.1 访问构造方法 

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

  • getConstructors()
  • getConstructor(Class<?>...parameterTypes)
  • getDeclaredConstructors()
  • getDeclaredConstructor(Class<?>..parameterTypes)

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

objeciClass.getDeclaredConstructor(String.class, int.class);

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

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

  Modifier 类中的常用解析方法如下:

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

方法的所有修饰符的典型代码如下:

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

 例题16.1 

 
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() {
		// TODO Auto-generated method stub
		System.out.println("s=" + s);
		System.out.println("i=" + i);
		System.out.println("i2=" + i2);
		System.out.println("i3=" + i3);
	}
}
//例题16.1
import java.lang.reflect.Constructor;
import com.mr.Demo1;
 
public class ConstructorDemo1 {
	public static void main(String[] args) {
		Demo1 d1 = new Demo1("10", "20", "30");
		Class<? extends Demo1> demoClass = d1.getClass();
		// 获得所有构造方法
		Constructor[] declaredConstructors = demoClass.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;
			try { // 如果该成员变量的访问权限为private,则抛出异常,即不允许访问
				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();
			}
		}
 
	}
}
//例题16.1

 运行结果:

16.1.2  访问成员变量

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

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

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

object. getDeclaredField("birthday");

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

 

例题16.2 

package com.mr;
 
public class Demo2 {
	int i;
	public float f;
	protected boolean b;
	private String s;
}
//例题16.2
import java.lang.reflect.Field;
import com.mr.Demo2;
 
public class FieldDemo {
	public static void main(String[] args) {
		Demo2 example = new Demo2();
		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,则抛出异常,即不允许访问
				try {
					isTurn = false;
					// 获得成员变量值
					System.out.println("修改前的值为:" + field.get(example));
					if (fieldType.equals(int.class)) { // 判断成员变量的类型是否为int型
						System.out.println("利用方法setInt()修改成员变量的值");
						field.setInt(example, 168); // 为int型成员变量赋值
					} else if (fieldType.equals(float.class)) { // 判断成员变量的类型是否为float型
						System.out.println("利用方法setFloat()修改成员变量的值");
						field.setFloat(example, 99.9F); // 为float型成员变量赋值
						// 判断成员变量的类型是否为boolean型
					} else if (fieldType.equals(boolean.class)) {
						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();
		}
	}
}
//例题16.2

 运行结果:

 16.1.3  访问成员方法

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

  • getMethods()
  • getMethod(String name, Class<?>...parameterTypes)
  • getDeclaredMethods()
  • 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 类中提供的常用方法如表16.5所示。

例题16.3 

package com.mr;
 
public class Demo3 {
	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();
	}
}
//例题16.3

 

import java.lang.reflect.*;
 
import com.mr.Demo3;
 
public class MethondDemo {
	public static void main(String[] args) {
		Demo3 demo = new Demo3();
		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,则抛出异常,即不允许访问
					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();
		}
	}
}
//例题16.3

16.2 Annotation 注解功能

16.2.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() default "<默认值>";
Class type() default void.class;
}

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

例题:

package 十六;

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型到成员
}

 例题2:

package 十六;

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

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

 例题3:

package 十六;

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

@Target(value = {ElementType.CONSTRUCTOR,ElementType.FIELD}) 		//构造方法,成员变量
@Retention(value = RetentionPolicy.RUNTIME)			//运行

public @interface MyAnnotation {
	String value() default "HAPPY";
	int i();
}
package 十六;

public class Demo {
	
	@MyAnnotation(i = 0)
	public Demo(){
		
	}
}

最后一个例题:

package 十六;

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 getld() {
		return id;
	}
	
	@Field_Method_Parameter_Annotation(describe = "设置编号")
	//成员 type 采用默认值注释方法
	public void setld(
			//注释方法的参数
			@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;
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值