package com.itheima.shipin.daili;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Collection;
public class ProxyTestII {
public static void main(String[] args) throws Exception {
Collection proxy3 = (Collection) Proxy.newProxyInstance(
// 匿名内部类
Collection.class.getClassLoader(),
new Class[] { Collection.class }, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method,
Object[] args) throws Throwable {
System.out.println("proxy.newProxyInstance");
return null;
}
});
proxy3.clear();
}
}
将以上的代码进行修改将其变成通用方法。
private static Object getProxy(final Object target,
final MyInterface myinterface) {
Object proxy3 = Proxy.newProxyInstance(
// 匿名内部类
target.getClass().getClassLoader(), target.getClass()
.getInterfaces(), new InvocationHandler() {
public Object invoke(Object proxy, Method method,
Object[] args) throws Throwable {
// long begintime = System.currentTimeMillis();
myinterface.beforMethod(method);
Object retVal = method.invoke(target, args);
myinterface.afterMethod(method);
// System.out.println("proxy.newProxyInstance");
// long endtime = System.currentTimeMillis();
// System.out.println(endtime - begintime);
return retVal;
}
});
return proxy3;
}
为了调试我们再做个MyInterface结构以及其实现类。
MyInterface.java
package com.itheima.shipin.daili;
import java.lang.reflect.Method;
public interface MyInterface {
public void beforMethod(Method method);
public void afterMethod(Method method);
}
MyInterfaceM.java
package com.itheima.shipin.daili;
import java.lang.reflect.Method;
public class MyInterfaceM implements MyInterface {
@Override
public void beforMethod(Method method) {
// TODO Auto-generated method stub
System.out.println("beginning heima");
}
@Override
public void afterMethod(Method method) {
// TODO Auto-generated method stub
System.out.println("end............");
}
}
再写测试方法。
public static void main(String[] args) {
// TODO Auto-generated method stub
final ArrayList target = new ArrayList();
Collection proxy = (Collection) getProxy(target, new MyInterfaceM());
proxy.add("abc");
proxy.add("abcd");
proxy.add("abcdf");
System.out.println(proxy);
}
运行结果
beginning heima
end............
beginning heima
end............
beginning heima
end............
beginning heima
end............
[abc, abcd, abcdf]