package com.jun.music.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.nio.file.attribute.AclEntry;
public class ProxyTest {
public static void main(String[] args) {
Message message = (Message) new MessageProxy().bind(new MessageImpl());
message.send();
}
}
interface Message{
public boolean send();
}
class MessageImpl implements Message{
@Override
public boolean send() {
System.out.println("发送成功");
return true;
}
}
class MessageProxy implements InvocationHandler {
private Object object;
public boolean connect() {
System.out.println("链接成功");
return true;
}
public void close() {
System.out.println("成功关闭");
}
public Object bind(Object object) {
this.object = object;
return Proxy.newProxyInstance(this.object.getClass().getClassLoader(), object.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object returnData = null;
if (connect()) {
returnData = method.invoke(object, args);
this.close();
}
System.out.println(returnData);
return returnData;
}
}
|