package com.test;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyTest {
public static void main(String[] args) {
ProxyService service = (ProxyService)Proxy.newProxyInstance(ProxyTest.class.getClassLoader(),
new Class[] {ProxyService.class}, new InvocationHandler() {
String name;
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().equals("name")) {
name = (String)args[0];
} else if (method.getName().equals("say")) {
System.out.println("my name is " + name);
}
return null;
}
});
service.name("john");
service.say();
ProxyService service2 = (ProxyService)Proxy.newProxyInstance(ProxyTest.class.getClassLoader(),
new Class[] {ProxyService.class}, new InvocationHandler() {
String name;
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().equals("name")) {
name = (String)args[0];
} else if (method.getName().equals("say")) {
System.out.println("my name is " + name);
}
return null;
}
});
service2.name("xxx");
service2.say();
service.say();
}
public interface ProxyService {
String name(String name);
void say();
}
}
网友评论