java代理 proxy
程序员文章站
2022-06-09 21:38:21
...
public interface Person {
String sing(String name);
String dance(String name);
}
public class LiuDeHua implements Person{
@Override
public String sing(String name) {
System.out.println("Liu sing" + name);
return "Thanks!";
}
@Override
public String dance(String name) {
System.out.println("Liu dance" + name);
return "Bay!";
}
}
public class LiuDeHuaProxy {
private Person person;
public LiuDeHuaProxy(Person person){
this.person = person;
}
public Person getProxy() {
return (Person) Proxy.newProxyInstance(LiuDeHuaProxy.class.getClassLoader(), person.getClass().getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("begin...");
// TODO Auto-generated method stub
if (method.getName().equals("sing")) {
System.out.println("sing...");
return method.invoke(person, args);
}
if (method.getName().equals("dance")) {
System.out.println("dance...");
return method.invoke(person, args);
}
return null;
}
});
}
public static void main(String[] args) {
LiuDeHuaProxy proxy = new LiuDeHuaProxy(new LiuDeHua());
// 获得代理对象
Person p = proxy.getProxy();
// 调用代理对象的sing方法
String retValue = p.sing("冰雨");
System.out.println(retValue);
// 调用代理对象的dance方法
String value = p.dance("江南style");
System.out.println(value);
}
}
public class LiuDeHuaProxy1 {
private Person person;
private LiuDeHuaProxy1(Person person){
this.person = person;
}
public String sing(String name){
System.out.println("sing...");
String s = person.sing(name);
System.out.println("...sign");
return s;
}
public String dance(String name){
System.out.println("dance...");
String s = person.dance(name);
System.out.println("...dance");
return s;
}
public static void main(String[] args) {
LiuDeHuaProxy1 proxy = new LiuDeHuaProxy1(new LiuDeHua());
proxy.sing("sing冰雨");
proxy.dance("dance江南style");
}
}
public class LiuDeHuaProxy2 implements MethodInterceptor{
private Object target;
public LiuDeHuaProxy2(Object target){
this.target = target;
}
public Object getProxyInstance(){
Enhancer en = new Enhancer();
en.setSuperclass(target.getClass());
en.setCallback(this);
return en.create();
}
@Override
public Object intercept(Object arg, Method method, Object[] args, MethodProxy proxy) throws Throwable {
System.out.println("start");
Object value = method.invoke(target, args);
System.out.println("end");
return value;
}
public static void main(String[] args) {
LiuDeHua ldh = (LiuDeHua) new LiuDeHuaProxy2(new LiuDeHua()).getProxyInstance();
ldh.sing("十年");
}
}
上一篇: javascript继承,原型,setInterval(前端面试)
下一篇: JAVA SE稀疏数组