通过注解注入对象使用.annotationType().getDeclaredMethods()得到

Person类
package com.introspector;

public class Person {
	private String name;
	private int age;
	private boolean gender;
	
	public boolean isGender() {
		return gender;
	}
	public void setGender(boolean gender) {
		this.gender = gender;
	}
	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类
package com.introspector;

public class PersonDao {
	private Person person;

	public Person getPerson() {
		return person;
	}
	
	@Injection(name="张一", age=11, gender=false)
	public void setPerson(Person person){
		this.person = person;
	}
}


Injection类

package com.introspector;

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

@Retention(RetentionPolicy.RUNTIME)
public @interface Injection {

	String name();

	int age();
	
	boolean gender() default true;

}



TestDemo类

		//得到PersonDao上person的属性描述器
		PropertyDescriptor pd = new PropertyDescriptor("person", PersonDao.class);
		Class clazz = pd.getPropertyType();
		Object p = clazz.newInstance();
		Method writeMethod = pd.getWriteMethod();
		
		Injection injection = writeMethod.getAnnotation(Injection.class);
                  //injection.annotationType返回的是interface com.introspector.Injection 接口再直接得到注解接口对应的方法
		Method[] methods = injection.annotationType().getDeclaredMethods();
		Field f = null;
		for(Method m : methods){
                           //直接往person的属性中注入
			f = p.getClass().getDeclaredField(m.getName());
			f.setAccessible(true);
			f.set(p, m.invoke(injection, null));
		}
		
		PersonDao pdo = new PersonDao();
		writeMethod.invoke(pdo, p);
		System.out.println(pdo.getPerson().getAge());
		System.out.println(pdo.getPerson().getName());
		System.out.println(pdo.getPerson().isGender());

猜你喜欢

转载自clazz.iteye.com/blog/2042911
今日推荐