javassist实现动态代理

创建被代理类

package javaassist;

public class Hello {
    public void say() {
        System.out.println("Hello");
    }
}

创建MethodHandler

package javaassist;

import java.lang.reflect.Method;

import javassist.util.proxy.MethodHandler;

public class MethondAop implements MethodHandler {

	@Override
	public Object invoke(Object arg0, Method arg1, Method arg2, Object[] arg3)
			throws Throwable {
		System.out.println("我来自代理");
		return arg2.invoke(arg0, arg3);
	}

}

创建测试类

package javaassist;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

import model.User;
import annotation.Column;
import annotation.Table;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.util.proxy.ProxyFactory;
import javassist.util.proxy.ProxyObject;

public class Test {
    public static void main(String[] args) throws Exception {
    	
    	
    	ProxyFactory proxyFactory=new ProxyFactory();
    	proxyFactory.setSuperclass(Hello.class);
    	Class<?> classes=proxyFactory.createClass();
    	MethondAop methondAop=new MethondAop();
    	Object ret=classes.newInstance();
    	((ProxyObject)ret).setHandler(methondAop);
    	((Hello)ret).say();
    }
}



运行结果

我来自代理
Hello

PS

ProxyFactory 的方法 public void setHandler(MethodHandler mi) ,已经过期,api给出的理由如下

Deprecated. since 3.12 use of this method is incompatible with proxy class caching. instead clients should call method ProxyObject.setHandler(MethodHandler) to set the handler for each newly created proxy instance. calling this method will automatically disable caching of classes created by the proxy factory. Sets the default invocation handler. This invocation handler is shared among all the instances of a proxy class unless another is explicitly specified.

转载于:https://my.oschina.net/u/3238650/blog/1579718

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值