如何用Bytebuddy有效地包装POJO?

时间:2016-06-09 07:09:55

标签: java proxy-classes byte-buddy

我想包装简单的POJO类。事情是我事先对这个课程一无所知,只是因为它是定制者和吸气剂的POJO。我想用我的Proxyclass替换这个类,这样每次客户端调用getter或setter时我都能拦截该调用。因此,当拦截调用时,我想做一些预先获取(或设置)操作,然后调用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() {}

而setter看起来一样。

但是当我从我的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

3 个答案:

答案 0 :(得分:3)

正如所指出的,你应该避免反射调用。在Byte Buddy中,使用@SuperCall注入:

public class GetterInterceptor {

  @RuntimeType
  public static Object intercept(@SuperCall Callable<?> zuper) throws Exception {
    preGetHandle();
    try {
       return zuper.call();
    } finally {
      postGetHandle();
    }
  }

  private static void preGetHandle() {}
  private static void postGetHandle() {}
}

对于setter,您不需要返回值,因此可以使用runnable。

答案 1 :(得分:0)

这种放缓的大部分只是通过反思做生意的成本。

考虑这个测试:

>>> result
... [(2, 4), (3, 8), (4, 5), (11, 3)]

我得到以下结果:

import java.lang.reflect.Method;
import java.util.Random;

public class Main {
    public interface Pojo {
        public long getId();
        public void setId(long id);
    }

    public static class SimplePojo implements Pojo  {
        private long id;
        @Override public long getId() { return id; }
        @Override public void setId(long id) {this.id = id;}
    }

    public static class DelegatingPojo implements Pojo {
        private final Pojo pojo;

        public DelegatingPojo(Pojo p) {this.pojo = p;}
        @Override public long getId() { return pojo.getId(); }
        @Override public void setId(long id) { pojo.setId(id);  }
    }

    public static class ReflectingPojo implements Pojo {
        private final Object delegate;
        private final Method getmethod;
        private final Method setmethod;

        public ReflectingPojo(Pojo p) throws NoSuchMethodException {
            this.delegate = p;
            this.getmethod = p.getClass().getMethod("getId");
            this.setmethod = p.getClass().getMethod("setId", Long.TYPE);
        }

        @Override public long getId() {
            Object result = null;
            Object[] allarguments = new Object[0];
            try {
                result = getmethod.invoke(delegate, allarguments);
            } catch (InvocationTargetException | IllegalAccessException e) {
                e.printStackTrace();
            }
            return (Long)result;
        }
        @Override public void setId(long id) {
            Object[] allarguments = new Object[]{id};
            try {
                setmethod.invoke(delegate, allarguments);
            } catch (InvocationTargetException | IllegalAccessException e) {
                e.printStackTrace();
            }
            return;
        }
    }

    public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException {
        Pojo pojo = new SimplePojo();
        Pojo proxy = new DelegatingPojo(pojo);
        Pojo refl = new ReflectingPojo(pojo);

        testTime(pojo);
        testTime(proxy);
        testTime(refl);
    }

    private static final int LOOP_COUNT = 10_000_000;
    private static void testTime(Pojo pojo) {
        long startTime = System.currentTimeMillis();
        Random random = new Random();

        for (int i = 0; i < LOOP_COUNT; i++) {
            pojo.setId(random.nextLong());
            pojo.getId();
        }


        long endTime = System.currentTimeMillis();
        System.out.println(pojo.getClass() + " time = " + (endTime - startTime));
    }
}

正如您所看到的,使用反射的速度大约是其两倍。这不应该是一个巨大的惊喜,那些try block和method.invoke调用意味着你正在做一大堆基础pojo不需要做的额外工作。

答案 2 :(得分:0)

这只是一个部分答案我害怕...反思是让你慢下来的,以便跳过反思,你的解决方案必须是这样的形式:

PojoProxyClass = new ByteBuddy()
            .subclass(myPojo)
            .method(ElementMatchers.nameStartsWith("get"))
            .intercept(
                    MethodDelegation.to(<pre method>)
                        .andThen(MethodDelegation.to(<getter on the proxy>)
                            .andThen(MethodDelegation.to(<post method>)))
            )
            ...

唉,我不知道bytebuddy voodoo到底是什么。它就在某处。