Javaアプリケーションの処理内で、特定のパッケージ配下にあるクラスの中で、指定の条件を満たすものを抽出したい場合があります。
例えば、アプリ実行中に特定のアノテーションが付与されたクラスを探したい 等がこれに該当します。
このような場合、FastClasspathScanner
を利用すると簡単に実現できます。
FastClasspathScanner
を用いると、classpathをスキャンして指定の条件に合うクラスを抽出することができます。
(追記: FastClasspathScanner
は ClassGraph
に名称が変更された? ようです)
準備
pom.xmlに以下を追記します。
<dependency> <groupId>io.github.lukehutch</groupId> <artifactId>fast-classpath-scanner</artifactId> <version>{lib-version}</version> </dependency>
今回のサンプルではバージョンとして 2.0.13 を指定しました
サンプル
@SampleAnnotation
というアノテーションを用意して、sample.app
パッケージ以下にあるクラスの中でそのアノテーションが付与されているクラスを取得します。
■サンプルコード
クラスに付与するアノテーション(@SampleAnnotation
)は以下です。(何の変哲もないアノテーションです)
import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Documented @Retention(RetentionPolicy.RUNTIME) public @interface SampleAnnotation { }
FastClasspathScanner
を用いて@SampleAnnotation
が付与されたクラスを探す処理は以下のように記述できます。
import io.github.lukehutch.fastclasspathscanner.FastClasspathScanner; public class SampleMain { public static void main(String[] args) { new FastClasspathScanner("sample.app") .matchClassesWithAnnotation(SampleAnnotation.class, clazz -> System.out.println("Found class : " + clazz.getName())) .scan(); } }
FastClasspathScanner#matchClassesWithAnnotation
で 対象のアノテーションを指定しています
■実行結果
Found class : sample.app.domain.Logic1 Found class : sample.app.util.Util1
(条件を明確に記載していないので分かりにくいのですが)@SampleAnnotation
が 付与されたクラスだけが抽出されました
補足
今回は、特定のアノテーションが付与されたクラスを探すサンプルを実行しましたが、FastClasspathScanner
では他にも色々な条件でクラス等を探すことができます。