簡體   English   中英

Java 8, Google Reflections -- 獲取帶注釋的類型作為注釋列表,而不是類<?>

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

StackOverflow 用戶! 我正在構建一個游戲,名為 Volts of Doom,用戶可以在其中編寫自己的 mod 並將其放入一個文件夾中,然后將其加載到游戲中(類似於 Minecraft Forge 之類的東西,除了這個游戲被設計為被修改) .

使用@Mod 注釋聲明了一個 mod(見下文)。 目前,我可以在正確的 /mods/ 目錄中找到 jar 文件,然后可以找到用 @Mod 注釋的類。 當我嘗試從類的 @Mod 注釋中讀取 modid 時,問題就出現了。

我正在使用 Google Reflections,其getTypesAnnotatedWith(Annotation.class)方法返回帶注釋的類的Set<Class<?>> ,但由於元素的類型為Class<?> ,而不是類型@Mod ,我可以' t 訪問那個必要的值。

如果當我嘗試檢索 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 :(
Set<Class<?>> set = reflections.getTypesAnnotatedWith(Mod.class);

為您提供被注釋的類型,如果您想檢查注釋本身,您也需要查看它們,例如通過以下方式

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM