前回のエントリでFastClasspathScanner
を利用して特定のアノテーションが付与されたクラスを抽出するサンプルを実行しました。
FastClasspathScanner
では、他にも色々な条件でクラス等を抽出できます。いくつかサンプルを試してみます
インターフェースクラスを全部取得する
あるパッケージ以下に存在する全てのインターフェースクラスを抽出する場合、以下のAPIを利用します
FastClasspathScanner#matchAllInterfaceClasses
■サンプルコード
sample.app.domain
というパッケージ以下に存在する全インターフェースクラスを取得する例です
import io.github.lukehutch.fastclasspathscanner.FastClasspathScanner; new FastClasspathScanner("sample.app.domain") .matchAllInterfaceClasses( clazz -> System.out.println("Found class: " + clazz.getName())) .scan();
■実行結果
Found class: sample.app.domain.Interface1 Found class: sample.app.domain.Interface1$InnerInterface Found class: sample.app.domain.Interface2 Found class: sample.app.domain.SampleInterface
特定のインターフェースを実装したクラスを取得する
特定のインターフェースを実装したクラスを取得する場合、以下のAPIを利用します
FastClasspathScanner#matchClassesImplementing
■サンプルコード
sample.app
というパッケージ以下に存在するクラスの中でSampleInterface
というインターフェースを実装したものを取得する例です
import io.github.lukehutch.fastclasspathscanner.FastClasspathScanner; new FastClasspathScanner("sample.app") .matchClassesImplementing(SampleInterface.class, clazz -> System.out.println("Found class: " + clazz.getName())) .scan();
■実行結果
Found class: sample.app.domain.Impl1 Found class: sample.app.domain.Impl3
特定のインターフェースを継承したサブインターフェースを取得する
特定のインターフェースを継承したインターフェースクラスを取得する場合、以下のAPIを利用します
FastClasspathScanner#matchSubinterfacesOf
■サンプルコード
sample.app
というパッケージ以下に存在するインターフェースの中でSampleInterface
というインターフェースを継承したものを取得する例です
import io.github.lukehutch.fastclasspathscanner.FastClasspathScanner; new FastClasspathScanner("sample.app") .matchSubinterfacesOf(SampleInterface.class, clazz -> System.out.println("Found class: " + clazz.getName())) .scan();
■実行結果
Found class: sample.app.domain.Interface1
特定のクラスを継承したサブクラスを取得する
特定のクラスを継承したサブクラスを取得する場合、以下のAPIを利用します
FastClasspathScanner#matchSubclassesOf
■サンプルコード
sample.app
というパッケージ以下に存在するクラスの中でAbstractSample
というクラスを継承したものを取得する例です
import io.github.lukehutch.fastclasspathscanner.FastClasspathScanner; new FastClasspathScanner("sample.app") .matchSubclassesOf(AbstractSample.class, clazz -> System.out.println("Found class: " + clazz.getName())) .scan();
■実行結果
Found class: sample.app.domain.SubClass Found class: sample.app.domain.SubClass$InnerSubClass
メソッドに特定のアノテーションが付与されたものを取得する
メソッドに特定のアノテーションが付与されているクラスとそのメソッドを取得する場合以下のAPIを利用します
FastClasspathScanner#matchClassesWithMethodAnnotation
■サンプルコード
sample.app.domain
というパッケージ以下に存在するクラスの中で@MethodAnnotation
というアノテーションが付与されているメソッドを持つクラスとそのメソッドを取得する例です
import io.github.lukehutch.fastclasspathscanner.FastClasspathScanner; new FastClasspathScanner("sample.app.domain") .matchClassesWithMethodAnnotation(MethodAnnotation.class, (clazz, method) -> System.out.println("Found : " + clazz.getName() + "#" + method.getName())) .scan();
■実行結果
Found : sample.app.domain.SimpleClass#printHello Found : sample.app.domain.SubClass#execute1 Found : sample.app.domain.SubClass#execute2