検索
ホームページJava&#&チュートリアルJava インターフェイスの実装を動的に取得するにはどうすればよいですか?

How Can I Dynamically Retrieve Java Interface Implementations?

Java でのインターフェイスの実装の動的取得

オブジェクト指向プログラミングでは、インターフェイスの実装のリストを取得すると有益な場合があります。プログラム的にインターフェイスが与えられます。 Java では、これはリフレクションなどのさまざまな手法を通じて実現できます。

1 つのアプローチは、クラスをイントロスペクトし、クラス情報を抽出するための便利なメカニズムを提供するリフレクション ライブラリを使用することです。リフレクションを使用してこれを実現する方法は次のとおりです。

import org.reflections.Reflections;
import org.reflections.SubTypesScanner;

// Define the interface of interest
interface Pet {}

// Implementations of the Pet interface
class Dog implements Pet {}
class Cat implements Pet {}

// Use Reflections to get a list of Pet implementations
Reflections reflections = new Reflections("package.containing.implementations");
Set<class extends pet>> petImplementations = reflections.getSubTypesOf(Pet.class);

// Iterate over and display the implementations
for (Class extends Pet> implementation : petImplementations) {
    System.out.println(implementation.getSimpleName()); // prints Dog, Cat
}</class>

あるいは、Java の ServiceLoader 機能を利用して、サービス プロバイダー インターフェイス (SPI) の実装を検出することもできます。

import java.util.ServiceLoader;

// Define the Pet interface as an SPI
interface Pet {}

// Implementations of the Pet interface
class Dog implements Pet {}
class Cat implements Pet {}

// Use ServiceLoader to load implemented services
ServiceLoader<pet> loader = ServiceLoader.load(Pet.class);

// Iterate over and display the implementations
for (Pet implementation : loader) {
    System.out.println(implementation.getClass().getSimpleName()); // prints Dog, Cat
}</pet>

この方法では、インターフェイスの完全な内容を含むファイルを resource/META-INF/services ディレクトリに作成して、インターフェイスを SPI として指定する必要があります。

別のオプションには、パッケージ レベルのアノテーションの定義が含まれます。

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

// Package-level annotation to define implementations
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PACKAGE)
public @interface MyPackageAnnotation {
    Class>[] implementationsOfPet() default {};
}

// Implementations of the Pet interface
class Dog implements Pet {}
class Cat implements Pet {}

// Define the package-level annotation in a package-info.java file
@MyPackageAnnotation(implementationsOfPet = {Dog.class, Cat.class})
package package.containing.implementations;

// Iterate over and display the implementations
Package[] packages = Package.getPackages();
for (Package p : packages) {
    MyPackageAnnotation annotation = p.getAnnotation(MyPackageAnnotation.class);
    if (annotation != null) {
        Class>[] implementations = annotation.implementationsOfPet();
        for (Class> implementation : implementations) {
            System.out.println(implementation.getSimpleName());
        }
    }
}

このアプローチは、ClassLoader がすでに認識しているパッケージに対してのみ機能することに注意してください。より徹底的な検索を行うには、URLClassLoaders を検討してください。ただし、ロードされたクラスに特有の制限事項に注意してください。

以上がJava インターフェイスの実装を動的に取得するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
JVMパフォーマンスと他の言語JVMパフォーマンスと他の言語May 14, 2025 am 12:16 AM

jvm'sperformanceiscompetitivewitherruntimes、sped、safety、andproductivityの提供

Javaプラットフォームの独立性:使用の例Javaプラットフォームの独立性:使用の例May 14, 2025 am 12:14 AM

javaachievesplatformedentenceTheThejavavirtualMachine(JVM)、avainwithcodetorunonanyplatformwithajvm.1)codescompiledintobytecode、notmachine-specificcode.2)

JVMアーキテクチャ:Java Virtual Machineに深く飛び込みますJVMアーキテクチャ:Java Virtual Machineに深く飛び込みますMay 14, 2025 am 12:12 AM

thejvmisanabstractcomputingMachineCrucialForrunningJavaProgramsDuetoitsPlatForm-IndopentInterChitecture.Itincludes:1)ClassLoaderForloadingClasses、2)Runtimedataareaforforforatastorage、3)executionEngineWithinterter、Jitcompiler、およびGarbagecolfecolfecolfececolfecolfer

JVM:JVMはOSに関連していますか?JVM:JVMはOSに関連していますか?May 14, 2025 am 12:11 AM

jvmhasacloserelationshiptheosasittrantesjavabytecodecodecodecodecodecodecodecodecodecodecodecodecodetructions、manageSmemory、およびhandlesgarbagecollection.thisrelationshipallowsjavatorunonvariousosenvirnments、Butalsedentsはspeedifediferentjvmbeviorhiorsandosendisfredediferentjvmbehbehioorysando

Java:一度書く、どこでも実行(wora) - プラットフォームの独立に深く潜るJava:一度書く、どこでも実行(wora) - プラットフォームの独立に深く潜るMay 14, 2025 am 12:05 AM

Javaの実装「Write and、Run Everywherewhere」はBytecodeにコンパイルされ、Java仮想マシン(JVM)で実行されます。 1)Javaコードを書き、それをByteCodeにコンパイルします。 2)JVMがインストールされたプラットフォームでByteCodeが実行されます。 3)Javaネイティブインターフェイス(JNI)を使用して、プラットフォーム固有の機能を処理します。 JVMの一貫性やプラットフォーム固有のライブラリの使用などの課題にもかかわらず、Woraは開発効率と展開の柔軟性を大幅に向上させます。

Javaプラットフォームの独立性:異なるOSとの互換性Javaプラットフォームの独立性:異なるOSとの互換性May 13, 2025 am 12:11 AM

javaachievesplatformentenceTheTheTheJavavirtualMachine(JVM)、CodetorunondifferentoperatingSystemswithOutModification.thejvmcompilesjavacodeplatform-IndopentedbyTecodeを承認することを許可します

Javaをまだ強力にしている機能Javaをまだ強力にしている機能May 13, 2025 am 12:05 AM

javaispowerfulfulduetoitsplatformindepentence、object-orientednature、richstandardlibrary、performancecapability、andstrongsecurityfeatures.1)platformendependenceallowseplicationStorunonaydevicesupportingjava.2)オブジェクト指向のプログラマン型

トップJava機能:開発者向けの包括的なガイドトップJava機能:開発者向けの包括的なガイドMay 13, 2025 am 12:04 AM

上位のJava関数には、次のものが含まれます。1)オブジェクト指向プログラミング、サポートポリ型、コードの柔軟性と保守性の向上。 2)例外処理メカニズム、トライキャッチ式ブロックによるコードの堅牢性の向上。 3)ゴミ収集、メモリ管理の簡素化。 4)ジェネリック、タイプの安全性の向上。 5)コードをより簡潔で表現力豊かにするためのAMBDAの表現と機能的なプログラミング。 6)最適化されたデータ構造とアルゴリズムを提供するリッチ標準ライブラリ。

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 Linux 新バージョン

SublimeText3 Linux 新バージョン

SublimeText3 Linux 最新バージョン

MantisBT

MantisBT

Mantis は、製品の欠陥追跡を支援するために設計された、導入が簡単な Web ベースの欠陥追跡ツールです。 PHP、MySQL、Web サーバーが必要です。デモおよびホスティング サービスをチェックしてください。

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Eclipse を SAP NetWeaver アプリケーション サーバーと統合します。