public class PersonImpl implements Person {
@Override
public void say() {
System.out.println("My name is liangwc");
}
}
定义一个代理类,实现InvocationHandler接口
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class PersonProxy implements InvocationHandler {
private Object target;
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("Hi~");
Object result = method.invoke(target, args);
System.out.println("What your name?");
return result;
}
public Object bind(Object target) {
this.target = target;
return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
}
}
测试类
public class Test {
public static void main(String args[]) {
PersonProxy personProxy = new PersonProxy();
Person person = (Person) personProxy.bind(new PersonImpl());
person.say();
}
}
定义一个Person接口public interface Person { void say();}定义一个Person接口实现类public class PersonImpl implements Person { @Override public void say() { System.out.println("My name is liangwc"); }}...