Java 8,Google Reflections -- 获取注释类型作为注释列表,而不是 Class<?>



StackOverflow ers!我正在制作一款游戏,即《末日电压》,用户可以在其中编写自己的MOD并将其放入文件夹中,然后将其加载到游戏中(类似于《我的世界锻造》,只是这款游戏是为改装而设计的(。

mod是用@mod注释声明的(如下所示(。目前,我可以在正确的/mods/目录中找到jar文件,然后可以找到用@Mod注释的类。当我试图从类的@Mod注释中读取modid时,问题就出现了。

我使用的是Google Reflections,它的getTypesAnnotatedWith(Annotation.class)方法返回带注释类的Set<Class<?>>,但由于元素的类型是Class<?>,而不是@Mod,所以我无法访问必要的值。

如果当我尝试检索modid或将类强制转换为可以访问modid的格式时,只得到编译器错误和ClassCastException,我如何检索该值?我理解为什么会出现异常(不能将超类强制转换为子类等(,但我找不到解决方案。。。。有什么想法吗?

我将提供一个我目前正在使用的不起作用的代码示例。

//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 :(
Set<Class<?>> set = reflections.getTypesAnnotatedWith(Mod.class);

获取被注释的类型,如果您希望检查注释本身,您也需要查看它们,例如以以下方式

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

最新更新