public class Man implements Human{
@Override
public void sex() {
System.out.println( "this is Man" );
}
}
public class Women implements Human{
@Override
public void sex() {
System.out.println( "this is Women" );
}
}
创建针对接口实现增强操作的代理
public class GodProxy implements Human{
Human huamnGenarator;
public GodProxy(Human huamnGenarator){
this.huamnGenarator = huamnGenarator;
}
@Override
public void sex() {
System.out.println( "God begin to make human" );
huamnGenarator.sex();
System.out.println(" End of work ");
}
}
代理实现效果
public class 静态代理 {
public static void main(String[] args) {
GodProxy proxy_1 = new GodProxy(new Man());
GodProxy proxy_2 = new GodProxy(new Women());
proxy_1.sex();
System.out.println("\n\n");
proxy_2.sex();
}
}
public interface YoungMan {
public void nickName();
}
创建两个接口实现类
public class Boy implements Human,YoungMan{
@Override
public void sex() {
System.out.println( "this is Man" );
}
@Override
public void nickName() {
System.out.println( "少年" );
}
}
public class Girl implements Human,YoungMan{
@Override
public void sex() {
System.out.println( "this is Women" );
}
@Override
public void nickName() {
System.out.println( "少女" );
}
}
public class GodForYoungProxy implements InvocationHandler {
private Object godForYoungProxy;
//参数为Object设计一个向上转型
public Object newProxyInstance(Object godForYoungProxy) {
this.godForYoungProxy = godForYoungProxy;
//this指的是GodForYoungProxy这个InvocationHandler实现类
System.err.println( godForYoungProxy.getClass().getName() );
return Proxy.newProxyInstance(godForYoungProxy.getClass().getClassLoader(), godForYoungProxy.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println(" God for Young begin to work ... ");
proxy = method.invoke(godForYoungProxy, args);
System.out.println(" End of work ");
return proxy;
}
}
代理实现效果
public class 动态代理 {
public static void main(String[] args) {
GodForYoungProxy godForYoungProxy = new GodForYoungProxy();
Human human = (Human) godForYoungProxy.newProxyInstance(new Boy());
YoungMan youngMan = (YoungMan) godForYoungProxy.newProxyInstance(new Boy());
human.sex();
youngMan.nickName();
//向上转型测试
// Object obj = new Girl();
// Girl girl = (Girl) obj;
// System.err.println(obj.getClass().getName());
// System.err.println(obj.getClass().getInterfaces().length);
// girl.nickName();
}
}
loader – the class loader to define the proxy class
interfaces – the list of interfaces for the proxy class to implement
h – the invocation handler to dispatch method invocations to =>将方法调用分派到的调用处理程序
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println(" God for Young begin to work ... ");
// proxy = method.invoke(godForYoungProxy, args);
System.out.println(" End of work ");
return proxy;
}