我想包装简单的 POJO 类。问题是我事先对那个类一无所知,只知道它是带有 setter 和 getter 的 POJO。我想用我的 Proxyclass 替换这个类,以便每次客户端调用 getter 或 setter 时,我都能够拦截该调用。所以当调用被拦截时,我想做一些pre-get(或set)操作,然后调用getter(或setter),然后再做一些post-get(或set)操作。我正在这样创建我的代理
private Pojo generatePojoProxy(Class<? extends PojoInterface> myPojo) {
Class<?> PojoProxyClass;
PojoProxyClass = new ByteBuddy()
.subclass(myPojo)
.method(ElementMatchers.nameStartsWith("get"))
.intercept(MethodDelegation.to(GetterInterceptor.class))
.method(ElementMatchers.nameStartsWith("set"))
.intercept(MethodDelegation.to(SetterInterceptor.class))
.name("Proxy" + myPojo.getName())
.make()
.load(myPojo.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();
Object pojoProxyInstance = null;
try {
pojoProxyInstance = PojoProxyClass.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
return (Pojo) pojoProxyInstance;
}
我的 GetterInterceptor 看起来像这样
public class GetterInterceptor {
@RuntimeType
public static Object intercept(@AllArguments Object[] allArguments, @Origin Method method, @Super(proxyType = TargetType.class) Object delegate) {
preGetHandle();
Object result = null;
try {
result = method.invoke(delegate, allArguments);
} catch (InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
}
postGetHandle();
return result;
}
private static void preGetHandle() {}
private static void postGetHandle() {}
和二传手看起来一样。
但是当我从我的 Proxyclass 实例中设置和获取某些东西时,它比初始 Pojo 类实例要慢得多(慢 1.5-2 倍)。难道我做错了什么?我相信,一定有办法让它更快。
任何帮助表示赞赏!
我通过以下方式测量性能
public class Main {
private static final int LOOP_COUNT = 10_000_000;
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
Pojo pojo = new Pojo();
Pojo myProxy = (Pojo) ProxyFactory.getInstance().getProxy(Pojo.class);
testTime(pojo);
testTime(myProxy);
}
private static void testTime(Pojo pojo) {
long startTime = System.currentTimeMillis();
Random random = new Random();
long totalSum = 0;
for (int i = 0; i<LOOP_COUNT; i++){
pojo.setId(random.nextLong());
totalSum += pojo.getId();
}
long endTime = System.currentTimeMillis();
System.out.println(pojo.getClass() + " time = " + (endTime-startTime) + " total= " + totalSum);
}
我的结果是
class Pojo time = 288 total= 1060564671495946244
class ProxyPojo time = 738 total= 5879857558672375335