javaclasscastexceptionreflections

Java 8, Google Reflections -- Get Annotated Types as List of Annotations, not Class<?>


StackOverflow-ers! I am building a game, namely Volts of Doom, in which users can write and place their own mods into a folder, which will then be loaded into the game (similarly to something like Minecraft Forge, except this game is designed to be modded).

A mod is declared with an @Mod Annotation, (seen below). Currently, I can find jar file in the correct /mods/ directory, and can then find classes annotated with @Mod. The problem arises when I try to read the modid from the classes' @Mod annotation.

I am using Google Reflections, whose getTypesAnnotatedWith(Annotation.class) method returns a Set<Class<?>> of annotated classes, but as the elements are of the type Class<?>, and not the type @Mod, I can't access that necessary value.

How can I retrieve that value, if all I get are compiler errors and ClassCastExceptions when I try to retrieve the modid or cast the class to a format which I can access the modid from? I understand why the exceptions are occurring (cannot cast a superclass to a subclass, etc), but I can't find a solution.... Any ideas?

I will provide a sample of the not-working code I am using for this currently.

//Make the annotation available at runtime:
@Retention(RetentionPolicy.RUNTIME)

//Allow to use only on types:
@Target(ElementType.TYPE)

public @interface Mod {
    String modid();
}
Reflections reflections = new Reflections(new URLClassLoader("My Class Loader")), new SubTypesScanner(false), new TypeAnnotationsScanner());

Set<Class<?>> set = reflections.getTypesAnnotatedWith(Mod.class);

//cannot access modid from this set :(

Solution

  • Set<Class<?>> set = reflections.getTypesAnnotatedWith(Mod.class);
    

    gets you the types that were annotated, if you wish to examine the annotations themselves, you need to look at them too, for example in the following way

    for(Class<?> clazz : set) {
       Mod mod = clazz.getAnnotation(Mod.class);
       mod.modid();
    }