java - 如何使用 ByteBuddy 创建没有公共构造函数的类的动态代理
问题描述
我想创建一个类 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)
解决方案
请注意,包私有构造函数只有在同一个运行时包中定义时才对类可见。默认情况下,Byte Buddy 在加载类而不指定ClassLoadingStrategy
. 如果一个包的名称相同但不是由同一个类加载器加载,则运行时包将不同。
我假设通过指定:
.load(Sample.class.getClassLoader(), ClassLoadingStrategy.Default.INJECTION)
尽管在另一个答案中解决了反射访问中断,但您的代理将按预期工作。但是请注意,此策略使用了不安全的 API,它可能不再适用于 JVM 的未来版本。
推荐阅读
- arrays - Go 模板打印数组的长度
- kotlin - 使用 readLine() 是否有效!!如果输入是 Int,则不添加 toInt()?
- jquery - 执行 GET 请求时如何修复 CORS 错误?
- android - 如何仅更新 RecyclerView 中特定项目中的一个视图?
- python - PySide6 中的错误 MDIWindow
- java - 一次比较多个变量时如何编写 compareTo 方法?
- javascript - 如何正确检索和更改存储在 jQuery 数组中的文本值?
- python - Smartsheet webhook 子范围奇怪的行为
- java - 未设置 id 时遇到 StaleObjectStateException
- http - Dart:从 HTTP 请求构造对象的接口代码设计