Home » Java » java – ByteBuddy create class from created class-Exceptionshub

java – ByteBuddy create class from created class-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have an interface with some methods (unknown count).

I want to create another interface with methods, which will have same name and parameter types, but not return types.

Then, I want use second created interface for create a new class by byteBuddy. But when I use the created interface for creating a new one, I get

IllegalStateException: Could not locate class file for
SecondInterface.

example code:

Class<?> clazz
= new ByteBuddy()
    .makeInterface()
    .name("secondInterface")
    .make()
    .load(classLoader)
    .getLoaded();

for (Method method : FirstInterface.class.getMethods()) {

    Class<?>[] classes = method.getParameterTypes();
    List<Class<?>> classList = new ArrayList<Class<?>>(Arrays.asList(classes));
    classList.add(Object.class);

    clazz
    = new ByteBuddy()
        .rebase(clazz)
        .defineMethod(method.getName() + "Reverse", Void.class, Modifier.PUBLIC)
        .withParameters(classList)
        .withoutCode()
        .make()
        .load(classLoader)
        .getLoaded();
}

What am I doing wrong? Is byteBuddy allowed to create a class from a another which was just created?

How to&Answers:

If you are rebasing a class, you are editing its already existing class file where all existing methods are retained. Is this really what you are trying to do here? I’d rather define a new interface and add the methods to it, then you will neither run into the exception.

The reason you are seeing this error is that you are loading the interface using a class loader that does not retain the original byte code as a resource what is required for future editing. Provide ClassLoadingStrategy.Default.WRAPPER_PERSISTENT as a second argument to load and you will get around it.