标签:实现 can out targe access exce vat row policy
代码如下:
/** * 注入的注解,为空,仅起标志作用 */ @Target({ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) @interface Inject { } /** * 获取 bean 的容器,必通通过容器获取,而不能使用 new,因为需要使用反射获取注解信息并进行注入 */ class Container { public static <T> T getBean(Class<T> clazz) { T obj = null; try { obj = clazz.newInstance(); Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { if (!field.isAnnotationPresent(Inject.class)) // 如果被@Inject注解了的话 continue; if (!field.canAccess(obj)) field.setAccessible(true); field.set(obj, field.getType().newInstance()); // 给它绑定一个对象 } } catch (IllegalAccessException | InstantiationException e) { throw new RuntimeException(e); } return obj; } } //测试 class DAO { public String getInfo() { return "hello"; } } class Service { @Inject private DAO dao; public void doSth() { System.out.println(dao.getInfo()); } public static void main(String[] args) { Container.getBean(Service.class).doSth(); } }
标签:实现 can out targe access exce vat row policy
原文地址:https://www.cnblogs.com/yuanyb/p/12043950.html