咱就直接实例开头了哈:
我们需要一个工具类:People(接口里面不一定非要是抽象方法哦!!!!大家可以自己扩展一下)
public interface People {
public String Information();
}
再来一个重写Information的实现类Teather
public class Teather implements People {
public String Information() {
// TODO Auto-generated method stub
System.out.println("The Teacher is teaching English");
return "Mr Liuzhi";
}
}
接下来就是主要的代码了,看看我是怎样实现的动态代理:
/*
* @author Mr liu
* 动态代理的基本步骤和操作
* 1、实现InvocationHandler,重写invoke方法
* 2、通过invoke的代理实例上处理方法调用并返回结果。(Runnable和invoke的区别就在于有无返回值)
* 3、找到要找代理的对象,然后实例化为代理对象,进行下一步操作
* 4、通过Proxy.newProxyInstance(类加载器,接口,InvocationHandler对象)实现动态代理
*/
public class Porxy implements InvocationHandler {
/**
* @param args
*/
Object obj;
public Porxy(Object obj){
this.obj=obj;
}
public Porxy(){
}
public static void main(String[] args) {
//需要代理对象
People person=new Teather();
//添加需要代理对象
InvocationHandler people=new Porxy(person);
//实现和加载代理对象
People people2=(People)Proxy.newProxyInstance(person.getClass().getClassLoader(), person.getClass().getInterfaces(),people);
String mess=people2.Information();
System.out.println(mess);
}
public Object invoke(Object arg0, Method arg1, Object[] arg2)
throws Throwable {
System.out.println("Porxy before");
Object result = arg1.invoke(this.obj, arg2);
return result;
}
}
输出结果:
结尾:希望各位大佬多多评论,你们的评论就是我学习的动力!!!!!