JDK反射

import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import org.apache.catalina.tribes.util.Arrays;

import com.inte.testInterface;

public class JDKProxyObject implements InvocationHandler {

    private Object target; // 维护目标对象
    public JDKProxyObject(Object target){
        this.target = target;
    }
    public static Object factory(Object obj){  
        Class cls = obj.getClass();  
        //通过Proxy类的newProxyInstance方法来返回代理对象,返回一个指定接口的代理类实例,该接口可以将方法调用指派到指定的调用处理程序  
        //cls.getClassLoader():返回该类的类加载器;cls.getInterfaces():确定此对象所表示的类或接口实现的接口;new ProxyObject(obj):指派方法调用的调用处理程序 
        return Proxy.newProxyInstance(cls.getClassLoader(), cls.getInterfaces(),new JDKProxyObject(obj));  
    }
    /**
     * 接口实现
     */
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
         System.out.println("函数调用前被拦截了:   " + method);  
            if(args != null){  
                //打印参数列表  
                System.out.println("方法有  " + args.length + "    个参数");  
                for(int i = 0; i < args.length; i ++){  
                    System.out.println(args[i]);  
                }  
            }  
            //利用反射机制动态调用原对象的方法  
             Object mo = method.invoke(target, args);  
             Class<? extends Object> class1 = target.getClass();
             Field[] declaredFields = class1.getDeclaredFields();
             for(Field f:declaredFields) {
                 System.out.println(f.getName()+" =============");
             }
             Method[] declaredMethods = class1.getDeclaredMethods();
             for(Method m:declaredMethods) {
                 //获取方法名及相应的参数列表
                 System.out.println(m.getName()+" ---------------"+Arrays.toString(m.getParameters()));
             }
            System.out.println("函数调用后进行处理 :   " + method);  
            return mo;  
    }  
     //测试代码      
    public static void main(String agr[]){  
        testInterface si = (testInterface)factory(new testInterfaceImpl());  
        si.show("测试代理");
    }  
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值