2011-05-18 41 views
3

我正在編寫一個定製的跨平臺序列化方法,它通過註釋類如下所示來支持自定義類型(標準類型爲字符串,數字,地圖,列表等):查找帶有特定註釋的加載類

@CompactTypeName("myapp.BetweenFilter") 
public static class BetweenFilter implements NumericFilter { 

    static { 
     CompactSerializer.registerClass(BetweenFilter.class); 
    } 

    ... 

    @SuppressWarnings("unused") 
    @Deserialize 
    private static BetweenFilter compactRead(DataInputStream ins) throws IOException { 
     return new BetweenFilter(ins.readInt(), ins.readInt()); 
    } 

    @SuppressWarnings("unused") 
    @Serialize 
    private void compactWrite(DataOutputStream ous) throws IOException { 
     ous.writeInt(from); 
     ous.writeInt(to); 
    } 

} 

問題是,那裏的靜態初始化程序會在序列化組件上創建運行時依賴項,而其他部分則不會(註釋在運行時不存在)被忽略。

爲了解決這個問題,而不是階級與CompactSerializer註冊本身,串行應該有找到類,並將其與給定類型名稱(「myapp.BetweenFilter」)相關聯的一些方法。

我該怎麼做?我知道這是可能的,因爲例如Spring-MVC可以自動找到@Controller的類。

+1

這個問題可能是相關的:http://stackoverflow.com/questions/259140/scanning-java-annotations-at-runtime – 2011-05-18 14:52:44

回答

3

您需要掃描類路徑。基本上是:你必須

  • 發現每類路徑元素(文件夾或jar)
  • 遍歷每個元素找到一個名爲的* .class所有(步行或者文件系統或者Jar條目)
  • 負載類
  • 檢查它們的註解(如果你找方法的註釋,掃描你的類路徑中的所有類的所有方法)

Spring有高度專業化的類來完成這一切。你可以從零開始寫這個功能,但這是一個巨大的痛苦。

+0

我請使用Phill Sacre發佈的鏈接中的Google Reflections – 2011-05-20 08:39:03

2

尋找更多有關註釋處理器在Java中6