惰性加载程序,可替代cglib?

时间:2018-10-25 13:32:47

标签: java javassist cglib

使用cglib,我可以使用以下代码创建延迟实例化的BigInteger:

Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(BigInteger.class);
enhancer.setCallback(
        new LazyLoader() {

            @Override
            public Object loadObject() throws Exception {
                // expensive computation here
                long totalCount = getTotalCount(totalCountExecutors); 
                return BigInteger.valueOf(totalCount);
            }
        });
totalCount =
        (BigInteger)
                enhancer.create(new Class[] {String.class}, new Object[] {"0"});

但是,以上内容在Java 11上发出警告,并且似乎不兼容发行版,因此我想迁移到其他库。 ByteBuddy ...很庞大,并且想要避免这么大的依赖性。可以用javassist(或任何其他“轻型”库)创建延迟加载代理吗?

3 个答案:

答案 0 :(得分:1)

使用Byte Buddy会很容易,但是如果您必须使用“轻量级”(我的连接在不到100毫秒的时间内下载3 MB),这就是您的方法:

ProxyFactory factory = new ProxyFactory();
factory .setSuperclass(BigInteger.class);
factory .setFilter(new MethodFilter() {
  @Override
  public boolean isHandled(Method m) {
     return !m.getName().equals("finalize");
  }
});

Class<?> clazz = factory.createClass();
MethodHandler handler = new MethodHandler() {

  private volatile Object delegate;

  @Override
  public Object invoke(Object self, Method method, Method proceed,
                       Object[] args) throws Throwable {
     Object delegate = this.delegate;
     if (delegate == null) {
       synchronized (this) {
         delegate = this.delegate;
         if (delegate == null) {
           this.delegate = delegate = loadObject();
         }
       }
     }
     return method.invoke(delegate, args);
 }

  private Object loadObject() throws Exception {
    // expensive computation here
    long totalCount = getTotalCount(totalCountExecutors); 
    return BigInteger.valueOf(totalCount);
  }
};

BigInteger instance = (BigInteger) clazz.newInstance();
((Proxy) instance).setHandler(handler);

但是请注意,Javassist面临着模块系统自身的问题,将来您可能需要进行另一次迁移。

答案 1 :(得分:0)

您可以使用 Javassist 库(http://www.javassist.org)吗?

例如,休眠正在大量使用Javassist代理来管理延迟加载: https://docs.jboss.org/hibernate/orm/4.2/javadocs/org/hibernate/proxy/pojo/javassist/JavassistLazyInitializer.html

您可能会从中得到启发吗?

答案 2 :(得分:0)

这是@zapl建议的完全没有任何第三方库的实现。我花了3分钟在Eclispe中创建此代码:我创建了一个类存根,然后使用“ Generate Delegate Methods ...”(生成委托方法...),然后使用“ Generate Getters and Setters ...”(生成Getter和Setters ...)。所有的荣誉都归@zapl。

import java.math.BigInteger;

public class MyBigInt extends BigInteger {

    private BigInteger delegate;

    public MyBigInt() {
        super("0");
    }

    private BigInteger getDelegate() {
        if (delegate == null) {
            delegate = computeMeHere();
        }
        return delegate;
    }

    public byte byteValue() {
        return getDelegate().byteValue();
    }

    public short shortValue() {
        return getDelegate().shortValue();
    }

    public BigInteger nextProbablePrime() {
        return getDelegate().nextProbablePrime();
    }

    public BigInteger add(BigInteger val) {
        return getDelegate().add(val);
    }

    public BigInteger subtract(BigInteger val) {
        return getDelegate().subtract(val);
    }

    public BigInteger multiply(BigInteger val) {
        return getDelegate().multiply(val);
    }

    public BigInteger divide(BigInteger val) {
        return getDelegate().divide(val);
    }

    public BigInteger[] divideAndRemainder(BigInteger val) {
        return getDelegate().divideAndRemainder(val);
    }

    public BigInteger remainder(BigInteger val) {
        return getDelegate().remainder(val);
    }

    public BigInteger pow(int exponent) {
        return getDelegate().pow(exponent);
    }

    public BigInteger gcd(BigInteger val) {
        return getDelegate().gcd(val);
    }

    public BigInteger abs() {
        return getDelegate().abs();
    }

    public BigInteger negate() {
        return getDelegate().negate();
    }

    public int signum() {
        return getDelegate().signum();
    }

    public BigInteger mod(BigInteger m) {
        return getDelegate().mod(m);
    }

    public BigInteger modPow(BigInteger exponent, BigInteger m) {
        return getDelegate().modPow(exponent, m);
    }

    public BigInteger modInverse(BigInteger m) {
        return getDelegate().modInverse(m);
    }

    public BigInteger shiftLeft(int n) {
        return getDelegate().shiftLeft(n);
    }

    public BigInteger shiftRight(int n) {
        return getDelegate().shiftRight(n);
    }

    public BigInteger and(BigInteger val) {
        return getDelegate().and(val);
    }

    public BigInteger or(BigInteger val) {
        return getDelegate().or(val);
    }

    public BigInteger xor(BigInteger val) {
        return getDelegate().xor(val);
    }

    public BigInteger not() {
        return getDelegate().not();
    }

    public BigInteger andNot(BigInteger val) {
        return getDelegate().andNot(val);
    }

    public boolean testBit(int n) {
        return getDelegate().testBit(n);
    }

    public BigInteger setBit(int n) {
        return getDelegate().setBit(n);
    }

    public BigInteger clearBit(int n) {
        return getDelegate().clearBit(n);
    }

    public BigInteger flipBit(int n) {
        return getDelegate().flipBit(n);
    }

    public int getLowestSetBit() {
        return getDelegate().getLowestSetBit();
    }

    public int bitLength() {
        return getDelegate().bitLength();
    }

    public int bitCount() {
        return getDelegate().bitCount();
    }

    public boolean isProbablePrime(int certainty) {
        return getDelegate().isProbablePrime(certainty);
    }

    public int compareTo(BigInteger val) {
        return getDelegate().compareTo(val);
    }

    public boolean equals(Object x) {
        return getDelegate().equals(x);
    }

    public BigInteger min(BigInteger val) {
        return getDelegate().min(val);
    }

    public BigInteger max(BigInteger val) {
        return getDelegate().max(val);
    }

    public int hashCode() {
        return getDelegate().hashCode();
    }

    public String toString(int radix) {
        return getDelegate().toString(radix);
    }

    public String toString() {
        return getDelegate().toString();
    }

    public byte[] toByteArray() {
        return getDelegate().toByteArray();
    }

    public int intValue() {
        return getDelegate().intValue();
    }

    public long longValue() {
        return getDelegate().longValue();
    }

    public float floatValue() {
        return getDelegate().floatValue();
    }

    public double doubleValue() {
        return getDelegate().doubleValue();
    }

    public long longValueExact() {
        return getDelegate().longValueExact();
    }

    public int intValueExact() {
        return getDelegate().intValueExact();
    }

    public short shortValueExact() {
        return getDelegate().shortValueExact();
    }

    public byte byteValueExact() {
        return getDelegate().byteValueExact();
    }
}