Java 8,Google Reflections-将带注释的类型作为注释列表而不是类获取>

问题描述 投票:0回答:1

StackOverflow-ers!我正在构建一个游戏,即《毁灭战士》,用户可以在其中编写自己的mod并将其放入文件夹中,然后将其加载到游戏中(类似于Minecraft Forge之类的东西,不同之处在于该游戏旨在进行修改) 。

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

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

如果尝试获取modid或将类强制转换为可从其访问modid的格式时,如果得到的只是编译器错误和ClassCastExceptions,我将如何获取该值?我知道为什么会发生异常(无法将超类转换为子类,等等),但是我找不到解决方案...。有什么想法吗?

我将提供当前正在为此使用的无效代码的示例。

//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 :(
java classcastexception google-reflections
1个回答
0
投票
Set<Class<?>> set = reflections.getTypesAnnotatedWith(Mod.class);
为您提供被注释的类型,如果您希望自己检查注释,则也需要查看它们,例如,通过以下方式查看

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

© www.soinside.com 2019 - 2024. All rights reserved.