//Global inv public class IocInv implements Interceptor { @Override public void intercept(Invocation inv) { IocKit.init(inv.getController()); inv.invoke(); } } public class IocKit { private IocKit() { } public static void init(Object clazz) { Field[] fields = clazz.getClass().getDeclaredFields(); for (Field field : fields) { Inject annotation = field.getAnnotation(Inject.class); if (annotation != null) { try { field.setAccessible(true); if (field.get(clazz) == null) { Object fieldValue = Class.forName(field.getType().getName()).newInstance(); if (fieldValue != null) { init(fieldValue); field.set(clazz, fieldValue); } else { throw new NullPointerException(field.getClass().getName()); } } } catch (Exception e) { e.printStackTrace(); } finally { field.setAccessible(false); } } } } } public class DemoController extends Controller { @Inject private DemoService demoService; public void index() { demoService.print(); render("/pages/index.html"); } } @Aop public class DemoService { @Inject private DemoDao dao; public void print() { dao.print(); } } @Aop public class DemoDao { public void print() { System.out.println("success"); } } 总感觉哪里不对,但是又说不上来。
最大的问题是这句:
Object fieldValue = Class.forName(field.getType().getName()).newInstance();
如果 Field 是个接口或者抽象类,这里肯定就异常了,无法被实例化,而且这里的创建方式没有体现被实例化的“实现类”的动态特性,不如 new 出来方便