您的位置:首页 > 其它

解析注解实现注解注入

2016-05-28 22:24 211 查看


解析注解实现注解注入

自定义注解
@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());

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息