fb-datax
fb-datax

Reputation: 23

Reflections and ByteBuddy

How can I use byte-buddy generated classes with "org.reflections"?

Example:

    Class<?> dynamicType = new ByteBuddy()
            .subclass(Object.class)
            .name("de.testing.SomeClass")
            .method(ElementMatchers.named("toString"))
            .intercept(FixedValue.value("Hello World!"))
            .make()
            .load(getClass().getClassLoader(),ClassLoadingStrategy.Default.INJECTION)
            .getLoaded();

Now I want to use org.reflections to find all subtypes of Object inside a specific Package:

Reflections reflections = new Reflections("de.testing");
    Set<Class<? extends Object>> objs = reflections.getSubTypesOf(Object.class);
    for (Class clazz : objs ) {
        log.info("{}",clazz.getName());
    }

Any ideas?

Upvotes: 2

Views: 944

Answers (1)

Rafael Winterhalter
Rafael Winterhalter

Reputation: 44077

As suggested in the comments, reflections scans the class path by querying class loaders for its resources. This does normally only work for standard class loaders whereas Byte Buddy creates classes in memory where they are not found using resource scanning.

You can work around this by storing Byte Buddy's classes in a jar file and loading this jar file manually using a URLClassLoader. Byte Buddy allows you to create a jar by .make().toJar( ... ). You can then provide this class loader to reflections which by default only scans the system class loader.

All this does however seem like quite a complex solution to a problem that could be easily solved by registering your types somewhere explicitly.

Upvotes: 1

Related Questions