package dynaticproxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class Ruint implements InvocationHandler{
private Object any_Object;
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object return_object = null;
System.out.println("打印开始。。。。。。。。。。。。。。");
return_object = method.invoke(any_Object, args);
System.out.println("打印结束。。。。。。。。。。。。。。。");
return return_object;
}
public Object bind(Object object){
this.any_Object = object;
/*
* 这里用到了this对象,也就是InvocationHandler的对象(包含invoke方法 的对象 );
* proxy是一个代理类,它不像静态代理那样去实现接口,而是通过一个方法把接口传进去,也相当于实现了接口(怎么实现的看jdk的源码),在传进去 * 一个添加业务处理方法的
return Proxy.newProxyInstance(any_Object.getClass().getClassLoader(),
any_Object.getClass().getInterfaces(), this);
}
public static void main(String[] args) {
Hello_interface_impl h1 = new Hello_interface_impl();
Ruint r = new Ruint(); /// 处理类
Hello_interface h2 = (Hello_interface)r.bind(h1);
h2.say_hello();
}
}
interface Hello_interface {
public void say_hello();
}
class Hello_interface_impl implements Hello_interface{
@Override
public void say_hello() {
System.out.println("......hello....");
}
}
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class Ruint implements InvocationHandler{
private Object any_Object;
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object return_object = null;
System.out.println("打印开始。。。。。。。。。。。。。。");
return_object = method.invoke(any_Object, args);
System.out.println("打印结束。。。。。。。。。。。。。。。");
return return_object;
}
public Object bind(Object object){
this.any_Object = object;
/*
* 这里用到了this对象,也就是InvocationHandler的对象(包含invoke方法 的对象 );
* proxy是一个代理类,它不像静态代理那样去实现接口,而是通过一个方法把接口传进去,也相当于实现了接口(怎么实现的看jdk的源码),在传进去 * 一个添加业务处理方法的
* 实现InvocationHandler接口的对象。(内部怎样调用invoke方法的看源码)。
* 可以把 实现InvocationHandler 接口的对象和proxy new 的实例分开写,分开写需要自己写得到 method类的方法。。。。
*/return Proxy.newProxyInstance(any_Object.getClass().getClassLoader(),
any_Object.getClass().getInterfaces(), this);
}
public static void main(String[] args) {
Hello_interface_impl h1 = new Hello_interface_impl();
Ruint r = new Ruint(); /// 处理类
Hello_interface h2 = (Hello_interface)r.bind(h1);
h2.say_hello();
}
}
interface Hello_interface {
public void say_hello();
}
class Hello_interface_impl implements Hello_interface{
@Override
public void say_hello() {
System.out.println("......hello....");
}
}