简体   繁体   中英

ByteBuddy create class from created class

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM