publicstaticvoidmain(String[] args){ Human proxyInstance = (Human) Proxy.newProxyInstance(Human.class.getClassLoader(), new Class[]{Human.class}, new ActionProxy()); proxyInstance.doEat("apple"); //proxyInstance.showAge(50); }
showAge 50 Exception in thread "main" java.lang.NullPointerException at com.sun.proxy.$Proxy0.showAge(Unknown Source) at com.example.javalearning.HumanTest.main(HumanTest.java:9)
@Override public Object invoke(Object proxy, Method method, Object[] args)throws Throwable { if(null != this.instance){ if (method.getName().equals("doEat")){ args[0] = "delicious " + args[0]; Object res = method.invoke(this.instance, args); return res; }elseif(method.getName().equals("showAge")){ Object res = method.invoke(this.instance, args); int i = (int)res - 10; return i; } } returnnull; } }
创建代理实例
1 2 3 4 5 6 7 8
publicclassHumanTest{ publicstaticvoidmain(String[] args){ Human zhangsan = new Chinese(); Human proxyInstance = (Human) Proxy.newProxyInstance(Human.class.getClassLoader(), new Class[]{Human.class}, new ActionProxy(zhangsan)); System.out.println(proxyInstance.doEat("hot pot")); System.out.println(proxyInstance.showAge(50)); } }