ByteBuddy如何在Android中为另一个由ByteBuddy创建的类创建子类?

huangapple go评论96阅读模式
英文:

ByteBuddy how to create a subclass of another ByteBuddy created Class in Android?

问题

我正在为Android编写Java代码,使用byte-buddy:1.10.17byte-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();

huangapple
  • 本文由 发表于 2020年10月27日 04:15:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/64544355.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定