import java.lang.reflect.*;
import java.util.HashMap;
interface Interface {
void say();
void sayMore(int i);
}
interface Interface2 {
void hello();
}
class Real implements Interface, Interface2 {
public void say() {System.out.println("fuck u"); }
public void sayMore(int i) {System.out.println(i);}
public void hello() {System.out.println("hello");}
}
class DynamicProxyHandler implements InvocationHandler {
private Object proxied;
private HashMap<Method,Integer> count;
DynamicProxyHandler(Object proxied) {
this.proxied = proxied;
this.count = new HashMap<>();
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//System.out.println(proxy); //這裏StackOverflow,應當是因爲toString中調用了invoke
if (count.containsKey(method)==false)
count.put(method,0);
count.replace(method,count.get(method)+1);
System.out.println(count);
return method.invoke(proxied,args);
}
}
public class Ans {
public static void consumer(Interface iface,int i) {
iface.say();
iface.sayMore(i);
}
public static void consumer(Interface2 iface) {
iface.hello();
}
public static void main(String[] args) {
Real obj = new Real();
//consumer(obj,1);
Interface obj2 = (Interface)Proxy.newProxyInstance(
Interface.class.getClassLoader(),
new Class[] {Interface.class,Interface2.class},
new DynamicProxyHandler(obj)
);
System.out.println(Interface.class.getClassLoader());
consumer(obj2,2);
consumer(obj2,2);
consumer((Interface2)obj2);
}
}
這個和加載器有關係,詳情見加載器