Javaでリフレクションを通じてプライベートフィールドを設定するための最短、最善の、クリーンな方法は何ですか?

アンドレアスをHauschild:

こんにちは私はすでにJavaでリフレクションで働いてきました。あなたが(例えばプライベートフィールドを注入する)Java標準を使用している場合しかし、あなたは仕事を得るために多くのコードを記述する必要があります。

Javaオブジェクトにプライベートフィールドを注入する最短の方法は何ですか?そこの実装は広く使用され、生産準備図書館でいますか?

アンドレアスをHauschild:

「ワンライナー」

FieldUtils.writeField(Object target, String fieldName, Object value, boolean forceAccess)

あなたのプロジェクトが使用している場合はApache Commonsのラングを反射によって値を設定するための最短の方法は、静的メソッドを使用することである「writeField」クラスの「org.apache.commons.lang3.reflect.FieldUtils」を

次の簡単な例では、フィールドpaymentServiceと書店・オブジェクトを示しています。プライベートフィールドが異なる値で2回設定されている方法のコードに示します。

import org.apache.commons.lang3.reflect.FieldUtils;

public class Main2 {
    public static void main(String[] args) throws IllegalAccessException {
        Bookstore bookstore = new Bookstore();

        //Just one line to inject the field via reflection
        FieldUtils.writeField(bookstore, "paymentService",new Paypal(), true);
        bookstore.pay(); // Prints: Paying with: Paypal

        //Just one line to inject the field via reflection
        FieldUtils.writeField(bookstore, "paymentService",new Visa(), true);
        bookstore.pay();// Prints Paying with: Visa
    }

    public static class Paypal implements  PaymentService{}

    public static class Visa implements  PaymentService{}

    public static class Bookstore {
        private  PaymentService paymentService;
        public void pay(){
            System.out.println("Paying with: "+ this.paymentService.getClass().getSimpleName());
        }
    }
}

あなたはMavenの中央を経由してのlibを取得することができます:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.8.1</version>
</dependency>

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=171578&siteId=1