StackOverflow-ers!我正在构建一个游戏,即末日之伏,用户可以编写自己的mod并将其放入文件夹中,然后将其加载到游戏中(类似于类似于《我的世界锻造》的东西,除了这个游戏被设计为可修改的)。
mod是用@Mod Annotation声明的(如下所示)。目前,我可以在正确的/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 :(发布于 2020-03-24 04:56:46
Set<Class<?>> set = reflections.getTypesAnnotatedWith(Mod.class);获取已批注的类型,如果您希望检查批注本身,则还需要查看它们,例如,按照以下方式
for(Class<?> clazz : set) {
Mod mod = clazz.getAnnotation(Mod.class);
mod.modid();
}https://stackoverflow.com/questions/60820680
复制相似问题