文章内容
1、定义Autowired注解
package com.ntan520.reflect;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Autowired {
}
2、定义一个service
package com.ntan520.reflect;
public class PersonService {
}
3、定义一个controller
package com.ntan520.reflect;
public class PersonController {
@Autowired
private PersonService personService;
public PersonService getPersonService() {
return personService;
}
}
4、实现Autowired
package com.ntan520.reflect;
import java.lang.reflect.Field;
public class TestAutowired {
public static void main(String[] args) throws Exception {
PersonController personController = new PersonController();
Class<? extends PersonController> clazz = personController.getClass();
//获取所有的属性值
Field[] declaredFields = clazz.getDeclaredFields();
for (Field field : declaredFields) {
String fieldName = field.getName();
System.out.println("fieldName:" + fieldName);
Autowired annotation = field.getAnnotation(Autowired.class);
//判断当前属性是否有Autowired这个注解
if (null != annotation) {
//设置属性可以访问
field.setAccessible(true);
//获取属性类型
Class<?> type = field.getType();
//通过属性类型创建实例
Object o = type.newInstance();
//把创建好的实例对象设置到controller上
field.set(personController, o);
}
}
System.out.println(personController.getPersonService());
}
}
5、输出日志
// 打印结果
fieldName:personService
com.ntan520.reflect.PersonService@63947c6b