接口实现接口动态代理的使用验证
接口java的动态代理,需要实现接口的所有方法
package com.chauncy;
public interface IAnimal {
void run();
void eat();
void sleep();
}
实现接口
package com.chauncy;
public class Dog implements IAnimal {
public void run() {
System.out.println("Dog is run...");
}
public void eat() {
System.out.println("Dog is eating...");
}
public void sleep() {
System.out.println("Dog is sleeping");
}
}
动态代理的使用
package com.chauncy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class AnimalProxy {
// 参数是接口类型
public static IAnimal getProxy(final IAnimal animal){
IAnimal instance;
// 获取类加载器
ClassLoader loader = animal.getClass().getClassLoader();
// 获取所有的接口 -- 被代理对象的所有接口
Class>[] interfaces = animal.getClass().getInterfaces();
// 用来执行被代理类需要执行的方法
InvocationHandler handler = new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 调用被代理类的方法
return method.invoke(animal, args);
}
};
//动态代理
instance = (IAnimal) Proxy.newProxyInstance(loader, interfaces, handler);
return instance;
}
}
验证
public static void main(String[] args) {
IAnimal proxy = AnimalProxy.getProxy(new Dog());
System.out.println("proxy的类型是 : " + proxy.getClass());
proxy.run();
}
// proxy的类型是 : class com.sun.proxy.$Proxy0
// Dog is run...



