Search code examples
javaandroidbyte-buddy

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


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.


Solution

  • 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();