リフレクションを使用してプライベートフィールドの値を設定する 質問する

リフレクションを使用してプライベートフィールドの値を設定する 質問する

私は2つのクラスを持っていますFather:Child

public class Father implements Serializable, JSONInterface {

    private String a_field;

    //setter and getter here

}

public class Child extends Father {
    //empty class
}

反省しながら、私は授業a_fieldで次のことを設定したいと思いますChild

Class<?> clazz = Class.forName("Child");
Object cc = clazz.newInstance();

Field f1 = cc.getClass().getField("a_field");
f1.set(cc, "reflecting on life");
String str1 = (String) f1.get(cc.getClass());
System.out.println("field: " + str1);

しかし例外があります:

スレッド「main」で例外が発生しました java.lang.NoSuchFieldException: a_field

しかし、試してみると:

Child child = new Child();
child.setA_field("123");

それは動作します。

setter メソッドを使用すると、同じ問題が発生します。

method = cc.getClass().getMethod("setA_field");
method.invoke(cc, new Object[] { "aaaaaaaaaaaaaa" });

ベストアンサー1

プライベート フィールドにアクセスするには、Field::setAccessibletrue に設定する必要があります。スーパー クラスからフィールドを取得できます。次のコードは機能します:

Class<?> clazz = Child.class;
Object cc = clazz.newInstance();

Field f1 = cc.getClass().getSuperclass().getDeclaredField("a_field");
f1.setAccessible(true);
f1.set(cc, "reflecting on life");
String str1 = (String) f1.get(cc);
System.out.println("field: " + str1);

おすすめ記事