透過Java 程式取得介面實作的綜合清單
在Java 中,您可能經常會遇到需要以程式設計方式檢索一組接口的情況。實作特定介面的類別。這可以透過多種方法來實現,其中一些涉及利用反射或其他專門技術。
使用反射庫:Reflections
Reflections 庫提供了一種便捷的方法來檢查類元資料和關係。透過利用Reflections 實例,您可以獲得一組擴充所需介面的類,如下例所示:
Reflections reflections = new Reflections("firstdeveloper.examples.reflections"); Set<Class<? extends Pet>> classes = reflections.getSubTypesOf(Pet.class);
使用ServiceLoader
ServiceLoader提供了一種在運行時定位和載入服務提供者實現的機制。要利用此技術檢索介面實現,您需要定義 ServiceProviderInterface (SPI) 並聲明其實作。以下程式碼說明了這個方法:
ServiceLoader<Pet> loader = ServiceLoader.load(Pet.class); for (Pet implClass : loader) { System.out.println(implClass.getClass().getSimpleName()); // prints Dog, Cat }
利用包級註解
另一種替代方法涉及使用包級註解。這種方法需要建立指定介面實作的自訂註解。以下程式碼範例展示如何定義註釋:
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PACKAGE) public @interface MyPackageAnnotation { Class<?>[] implementationsOfPet() default {}; }
要在套件中聲明註釋,請建立一個名為package-info.java 的檔案並包含以下內容:
@MyPackageAnnotation(implementationsOfPet = {Dog.class, Cat.class}) package examples.reflections;
然後,您可以使用以下程式碼擷取介面實作:
Package[] packages = Package.getPackages(); for (Package p : packages) { MyPackageAnnotation annotation = p.getAnnotation(MyPackageAnnotation.class); if (annotation != null) { Class<?>[] implementations = annotation.implementationsOfPet(); for (Class<?> impl : implementations) { System.out.println(impl.getSimpleName()); } } }
以上是如何以程式設計方式取得 Java 中介面實現的完整清單?的詳細內容。更多資訊請關注PHP中文網其他相關文章!