这个是给collection代理,只能他的子类才能做目标类,也可以将目标抽取出来,不过代码就要改变了
这下面的代码是张老师讲的时候,我根据他讲的理解着写的
- public class ProxyDemo
- {
- public static void main(String[] args)
- {
- Collection set=new HashSet();
- Collection set2=(Collection)show(set,new myAdvice());
- set2.add("one");
- set2.add("klds");
- System.out.println(set2.size());
- }
-
- public static Object show(final Object target ,final Advice advice)
- {
- Object obj=Proxy.newProxyInstance(
- target.getClass().getClassLoader(),
- target.getClass().getInterfaces(),
- new InvocationHandler()
- {
- public Object invoke(Object proxy, Method method,
- Object[] args) throws Throwable {
- advice.beforMethod();
- Object reVal=method.invoke(target, args);
- advice.afterMethod();
- return reVal;
- }
-
- }
- );
- return obj;
- }
-
- }[code]public class myAdvice implements Advice {
- public void beforMethod() {
- System.out.println("方法前");
- }
- public void afterMethod() {
- System.out.println("方法后");
- }
- }[code]
- public interface Advice
- {
- void beforMethod();
- void afterMethod();
- }
复制代码 [/code][/code] |