[英]How can I find all classes on the classpath that have a specific method annotation?
我想在 Java 中實現一個基於注解的初始化機制。 具體來說,我定義了一個注釋:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Initialization {
/**
* If the eager initialization flag is set to <code>true</code> then the
* initialized class will be initialized the first time it is created.
* Otherwise, it will be initialized the first time it is used.
*
* @return <code>true</code> if the initialization method should be called
* eagerly
*/
boolean eager() default false;
}
另外,我有一個界面:
public interface SomeKindOfBasicInterface {}
我想在我的類路徑上找到SomeKindOfBasicInterface
class 的每個實現,該類路徑在方法上有@Initialization
注釋。 我正在查看 Spring 的MetaDataReader
工具,它看起來是在我執行此操作時推遲加載其他SomeKindOfBasicInterface
實現的最佳方式......但我不確定如何進行我所描述的搜索。 有小費嗎?
您可以使用Reflections ,這是一個 Java 運行時元數據分析工具。 我用它來獲取給定類型的所有子類型,但它也可以處理您的情況。
我基本上會創建一個BeanPostProcessor實現,可能基於CommonAnnotationBeanPostProcessor 。 然后我設置了組件掃描,它掃描類路徑並選擇所有符合您的規范的 bean。 初始化 bean 時,您的后處理器將運行。
我知道我假設您正在尋找豆類。 如果不是這種情況,您可能必須自己掃描類路徑。
您可以使用javassist在您的類中找到注釋,甚至在加載它們之前,但您需要直接閱讀 .class 文件,這可能意味着您自己打開 JAR 等。此外,您需要知道在哪里尋找類。 您不能只向運行時詢問BasicInterface
的所有子類。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.