英文:
ByteBuddy how to create a subclass of another ByteBuddy created Class in Android?
问题
我正在为Android编写Java代码,使用byte-buddy:1.10.17
和byte-buddy-android:1.10.17
来动态创建类。我想动态创建一个类,它将是另一个动态创建类的子类。
以下是我想要实现的示例代码:
AndroidClassLoadingStrategy loadingStrategy = new AndroidClassLoadingStrategy.Wrapping(context.getCacheDir());
DynamicType.Builder builder = new ByteBuddy().subclass(Object.class).name("TestParentClass");
Class testParentClass = builder.make().load(Test.class.getClassLoader(), loadingStrategy).getLoaded();
builder = new ByteBuddy().subclass(testParentClass).name("TestChildClass");
Class testChildClass = builder.make().load(Test.class.getClassLoader(), loadingStrategy).getLoaded();
但是在创建子类时我遇到了Caused by: java.lang.ClassNotFoundException: Didn't find class "TestParentClass"
的错误。
我还查看了这个问题,但它并没有起作用。
英文:
I am writing a java code for android using byte-buddy:1.10.17
and byte-buddy-android:1.10.17
to dynamically create classes. I want to dynamically create a class which would be sub class of another dynamically created class.
Here is a sample code of what I want to do
AndroidClassLoadingStrategy loadingStrategy = new AndroidClassLoadingStrategy.Wrapping(context.getCacheDir());
DynamicType.Builder builder = new ByteBuddy().subclass(Object.class).name("TestParentClass");
Class testParentClass = builder.make().load(Test.class.getClassLoader(), loadingStrategy).getLoaded();
builder = new ByteBuddy().subclass(testParentClass).name("TestChildClass");
Class testChildClass = builder.make().load(Test.class.getClassLoader(), loadingStrategy).getLoaded();
but I am getting Caused by: java.lang.ClassNotFoundException: Didn't find class "TestParentClass"
when creating the child class.
I also have checked this question but it did not work at all.
答案1
得分: 1
不要使用Test的类加载器。它会在你的类路径中寻找一个类文件。对于动态类TestParentClass,将不会有任何类文件。相反,从TestParentClass获取类加载器:
Class testChildClass = builder.make().load(testParentClass.getClassLoader(), loadingStrategy).getLoaded();
英文:
Don't use the class-loader of Test. That will be looking for a class file in your classpath. There will be none for the dynamic class TestParentClass. Instead, get the class-loader from TestParentClass:
Class testChildClass = builder.make().load(testParentClass.getClassLoader(), loadingStrategy).getLoaded();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论