首先先定义一个Autowired的注解类
import java.lang.annotation.*;
//@Retention元注解在这里表示该注解保留到运行时期。
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Inherited
@Documented
public @interface Autowired {
}
定义一个Service类
public class Service {
}
定义一个Controller类,用自定义的Autowired进行注入
public class Controller {
@Autowired
private Service service;
public Service getService() {
return service;
}
}
最后写一个测试类
import java.util.stream.Stream;
public class Test {
public static void main(String[] args) {
Controller controller = new Controller();
Class<? extends Controller> clazz = controller.getClass();
Stream.of(clazz.getDeclaredFields()).forEach(field -> {
//判断每个属性是否有注解
Autowired annotation = field.getAnnotation(Autowired.class);
if(annotation!=null){
//通过setAccessible(true)的方式关闭安全检查就可以达到提升反射速度的目的
field.setAccessible(true);
Class<?> type = field.getType();
Object o = null;
try {
o = type.newInstance();
field.set(controller,o);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
});
System.out.println(controller.getService());
}
}
这样我们就完成了autowired的自定义了