1.定义一个注解
//运行时去动态获取注解信息
@Retention(RetentionPolicy.RUNTIME)
//作用于局部变量
@Target(ElementType.FIELD)
public @interface Autowired {
}
2.使用
@Test
public void testAutowired(){
UserController userController = new UserController();
Class<? extends UserController> clazz = userController.getClass();
Stream.of(clazz.getDeclaredFields()).forEach(field ->{
Autowired annotation = field.getAnnotation(Autowired.class);
if(annotation!=null){
//保证能访问private修饰的成员变量
field.setAccessible(true);
Class<?> type = field.getType();
try {
Object object = type.getConstructor().newInstance();
field.set(userController,object);
} catch (Exception e) {
e.printStackTrace();
}
}
});
System.out.println(userController.getUserService());
}