如何使用ByteBuddy创建没有公共构造函数的类的动态代理

时间:2018-11-14 17:45:12

标签: java reflection cglib byte-buddy

我想创建一个Sample类的动态代理,该类具有两个没有公共构造函数的类,它无法正常工作并给出错误。但是,如果我将构造函数设置为Public,则可以正常工作。字节伙伴中是否有可能实现这一目标?

还可以将addToList(..)方法设置为非公开吗?

示例代码:

public class Sample {
    private String name;
    private String college;
    private String id;
    private List<String> fieldList = new LinkedList<>();

     Sample() {
        //some code
        System.out.println("No arg constructor invoked");
    }

     Sample(String id) {
        this();
        this.id = id;
    }

    public String getId() {
        return this.id;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        System.out.println("Setting name: "+ name);
        this.name = name;
    }


    public String getCollege() {
        return college;
    }

    public void setCollege(String college) {
        System.out.println("Setting college: "+college);
        this.college = college;
    }

    public void addToList(String fieldName){
        fieldList.add(fieldName);
    }

    public List<String> getFieldList() {
        return Collections.unmodifiableList(fieldList);
    }

    public static Sample getProxyObject(String id) {
        Sample proxyObj = null;
        try {
            Class<? extends Sample> dynamicType = new ByteBuddy()
                    .subclass(Sample.class, ConstructorStrategy.Default.IMITATE_SUPER_CLASS )
                    .method(ElementMatchers.nameStartsWith("set"))
                    .intercept(MethodDelegation.to(new GreetingInterceptor()))
                    .make()
                    .load(Sample.class.getClassLoader())
                    .getLoaded();
            proxyObj = dynamicType.getConstructor(String.class).newInstance(id);
        } catch (Exception ex){
            ex.printStackTrace();
        }
        return proxyObj;
    }

    public static Sample getProxyObject() {
        Sample proxyObj = null;
        try {
             proxyObj = new ByteBuddy()
                    .subclass(Sample.class)
                    .method(ElementMatchers.nameStartsWith("setName"))
                    .intercept(MethodDelegation.to(new GreetingInterceptor()))
                    .make()
                    .load(Sample.class.getClassLoader())
                    .getLoaded().newInstance();
        } catch (Exception ex){
            ex.printStackTrace();
        }
        return proxyObj;
    }

    public static class GreetingInterceptor {
        public void abc(@SuperCall Callable<Void> zuper, @Origin Method method, @Super Sample parentObj, @This Object myself, @AllArguments Object[] args) {
            try {

                parentObj.addToList(method.getName());
                zuper.call();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

    }
}

要测试的主类:

public class SampleMain {
public static void main(String[] args) {
    System.out.println("===Scenario 1=====");
    Sample proxyObject = Sample.getProxyObject();
    proxyObject.setName("John Doe");

    System.out.println("===Scenario 2=====");
    proxyObject.getFieldList().stream().forEach(System.out::println);
    Sample proxyObject1 = Sample.getProxyObject("id123");
    proxyObject1.setName("John Doe");
    proxyObject1.setCollege("MIT");

    System.out.println("Id is: "+proxyObject1.getId());

    proxyObject1.getFieldList().stream().forEach(System.out::println);
} 
}

错误跟踪:

===场景1 =====

Exception in thread "main" java.lang.IllegalAccessError: tried to access method com.algorithm.Sample.<init>()V from class com.algorithm.Sample$ByteBuddy$J74XiIU8
    at com.algorithm.Sample$ByteBuddy$J74XiIU8.<init>(Unknown Source)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at java.lang.Class.newInstance(Class.java:442)
    at com.algorithm.Sample.getProxyObject(Sample.java:88)
    at com.algorithm.SampleMain.main(SampleMain.java:6)

2 个答案:

答案 0 :(得分:1)

如果protected构造函数没问题,那么:

  1. Sample()更改为protected Sample()以使方案1起作用:这使得从ByteBuddy产生的子类中可以访问无参数构造函数。
  2. Sample(String id)更改为protected Sample(String id),然后在getProxyObject(String id)中更改

    proxyObj = dynamicType.getConstructor(String.class).newInstance(id);
    

    Constructor<? extends Sample> ctor = dynamicType.getDeclaredConstructor(String.class);
    ctor.setAccessible(true);
    proxyObj = ctor.newInstance(id);
    

    这使方案2起作用。 ConstructorStrategy.Default.IMITATE_SUPER_CLASS在子类中生成相同的受保护构造函数,因此您需要使用getDeclaredConstructor()来获取它,然后使其可访问。

您还可以保护addToList(..),因为GreetingInterceptor可以访问它,它也可以正常工作。

答案 1 :(得分:1)

请注意,只有在同一运行时包中定义了类时,包私有构造函数才对类可见。默认情况下,字节好友在加载类而不指定ClassLoadingStrategy时会创建一个新的类加载器。如果一个软件包的名称相同,但没有由相同的类加载器加载,则运行时软件包将有所不​​同。

我假设通过指定:

.load(Sample.class.getClassLoader(), ClassLoadingStrategy.Default.INJECTION)

尽管其他答案中提到的反射性访问已损坏,但您的代理仍将按预期工作。但是请注意,此策略使用了不安全的API,在将来的JVM版本中可能不再起作用。