package com.zysstart.reflect4;
import sun.security.jca.GetInstance;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class MyDynamic {
public static void main(String[] args) {
Bird boy = new Bird("赵玉顺");
Flyable fly = (Flyable) ProxyInstance.getProxyInstance(boy);
fly.fly();
}
}
interface Flyable {
String fly();
}
class Bird implements Flyable{
private String name;
public Bird(String name) {
this.name = name;
}
@Override
public String fly() {
System.out.println(name + "在天上高昂的飞翔!");
return name;
}
}
class ProxyInstance {
public static Object getProxyInstance(Object obj) {
InvocationHandler h = new ProxyHander(obj);
return Proxy.newProxyInstance(obj.getClass().getClassLoader(),obj.getClass().getInterfaces(),h);
}
}
class ProxyHander implements InvocationHandler{
private Object obj;//被代理对象
public ProxyHander(Object obj) {
this.obj = obj;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("代理开始");
Object value = method.invoke(obj,args);
System.out.println("代理结束");
return value;
}
}