8

フィールドからインスタンスを取得する方法はありますか?
サンプルコードは次のとおりです。

public class Apple {
    // ... a bunch of stuffs..
}

public class Person {
    @MyAnnotation(value=123)
    private Apple apple;
}

public class AppleList {
    public add(Apple apple) {
        //...
    }
}

public class Main {
    public static void main(String args[]) {
        Person person = new Person();
        Field field = person.getClass().getDeclaredField("apple");

        // Do some random stuffs with the annotation ...

        AppleList appleList = new AppleList();

        // Now I want to add the "apple" instance into appleList, which I think
        // that is inside of field.

        appleList.add( .. . // how do I add it here? is it possible?

        // I can't do .. .add( field );
        // nor .add( (Apple) field );
    }
}

注釈付きで使用しているため、Reflectionを使用する必要があります。これは単なる「サンプル」であり、AppleList.add(Apple apple)実際には、クラスからメソッドを取得して呼び出すことにより、メソッドが呼び出されます。

そうすることで、次のようになります。method.invoke( appleList, field );

原因:java.lang.IllegalArgumentException: argument type mismatch

*編集* これは同じことを探している人に役立つかもしれません。

クラスPersonの場合、2つ以上のApple変数があります。

public class Person {
    private Apple appleOne;
    private Apple appleTwo;
    private Apple appleThree;
}

フィールドを取得すると、次のようになります。

Person person = new Person();
// populate person
Field field = person.getClass().getDeclaredField("appleTwo");
// and now I'm getting the instance...
Apple apple = (Apple) field.get( person );
// this will actually get me the instance "appleTwo"
// because of the field itself...

最初は、行だけを見て、(Apple) field.get( person );
Appleクラスに一致するインスタンスを取得することになると思いました。
だから私は疑問に思いました:「どのAppleが戻ってくるのか?」

4

1 に答える 1

13

フィールドはそれ自体がリンゴではなく、単なるフィールドです。これはインスタンスフィールドであるため、値を取得する前に宣言クラスのインスタンスが必要です。あなたが欲しい:

Apple apple = (Apple) field.get(person);

...もちろん、参照されるインスタンスのappleフィールドにデータが入力された後。person

于 2012-10-11T21:05:49.363 に答える