解析注解实现注解注入
@Retention(RetentionPolicy.RUNTIME)
public @interface InjectPerson {
String name();
int age();
}
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;
}
}
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 {
PropertyDescriptor pd = new PropertyDescriptor("person",PersonDao.class);
Class clazz = pd.getPropertyType();
Object person = clazz.newInstance();
Method setPerosn = pd.getWriteMethod();
InjectPerson inject = setPerosn.getAnnotation(InjectPerson.class);
Method[] methods = inject.getClass().getMethods();
for(Method m : methods){
String methodName = m.getName();
try{
Field f = Person.class.getDeclaredField(methodName);
Object value = m.invoke(inject, null);
f.setAccessible(true);
f.set(person, value);
}catch (Exception e) {
continue;
}
}
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 {
Field f = PersonDao.class.getDeclaredField("person");
Class clazz = f.getType();
Person person = (Person) clazz.newInstance();
InjectPerson inject = f.getAnnotation(InjectPerson.class);
Method ms [] = inject.getClass().getMethods();
for(Method m : ms){
String methodName = m.getName();
try{
PropertyDescriptor pd = new PropertyDescriptor(methodName,Person.class);
Method set = pd.getWriteMethod();
set.invoke(person, m.invoke(inject, null));
}catch (Exception e) {
continue;
}
}
PersonDao dao = new PersonDao();
f.setAccessible(true);
f.set(dao, person);
System.out.println(dao.getPerson().getAge());
System.out.println(dao.getPerson().getName());
}
}