解析注解实现注解注入

解析注解实现注解注入

  • 自定义注解
@Retention(RetentionPolicy.RUNTIME)
public @interface InjectPerson {

	String name();

	int age();

}
  • Person类
public class Person {
	
	private String name;
	private int age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
}
  • PersonDao
public class PersonDao {

	@InjectPerson(name="老王",age=23) private Person person;

	public Person getPerson() {
		return person;
	}

	@InjectPerson(name="老张",age=23)
	public void setPerson(Person person) {
		this.person = person;
	}
	
}
  • 解析注解实现注解注入
public class Test {

	public static void main(String[] args) throws Exception {
		
		//1.得到要注入的属性
		PropertyDescriptor pd = new PropertyDescriptor("person",PersonDao.class);
		
		//2.得到要注入的属性需要的类型
		Class clazz = pd.getPropertyType();  //Person
		
		//3.创健属性需要的对象
		Object person = clazz.newInstance();
		
		//4.得到属性的写方法
		Method setPerosn = pd.getWriteMethod();
		
		//5.反射出方法上声明的注解
		InjectPerson inject = setPerosn.getAnnotation(InjectPerson.class);
		
		//6.得到注解上声明的信息,填充person对象
		Method[] methods = inject.getClass().getMethods();
		for(Method m : methods){
			String methodName = m.getName();  //name or age
			try{
				Field f = Person.class.getDeclaredField(methodName);
				Object value = m.invoke(inject, null);  //得到注解上配置的属性的值
				f.setAccessible(true);
				f.set(person, value);
			}catch (Exception e) {
				continue;
			}
			
		}
		
		
		//7.把填充了数据的person通过setPerson方法整到personDao对象上
		PersonDao dao = new PersonDao();
		setPerosn.invoke(dao, person);
		
		System.out.println(dao.getPerson().getName());
		
	}

}
  • 直接从PersonDao中得到Person实现注入
public class Test2 {

	public static void main(String[] args) throws Exception {
		
		//1.得到需要注入的属性
		Field f = PersonDao.class.getDeclaredField("person");
		
		//2.得到属性需要的 类型
		Class clazz = f.getType();
		
		//3.创建person
		Person person = (Person) clazz.newInstance();
		
		//4.反射属性的注解,
		InjectPerson inject = f.getAnnotation(InjectPerson.class);
		
		//5.并用注解的信息填充person
		Method ms [] = inject.getClass().getMethods();
		for(Method m : ms){
			String methodName = m.getName();  //name( ) age()
			//看person对象上有没有注解与之对应的属性
			try{
				PropertyDescriptor pd = new PropertyDescriptor(methodName,Person.class);
				Method set = pd.getWriteMethod();  //setname setage
				set.invoke(person, m.invoke(inject, null));
			}catch (Exception e) {
				continue;
			}
		}
		
		//6.把person赋给dao
		PersonDao dao = new PersonDao();
		f.setAccessible(true);  //person
		f.set(dao, person);
		
		
		System.out.println(dao.getPerson().getAge());
		System.out.println(dao.getPerson().getName());
		
		
		
	}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值