2017-11-19 6 views
0

私の場合:特定のアノテーションがある場合は各プロパティのオブジェクトをチェックし、そうであればプロパティをnullに設定する関数を作成します。しかし、私は問題に直面しています:プロパティがコレクションであるかどうかをチェックするには、アノテーションがある場合はコレクションの各要素を調べる必要があります。新しいチェックされたコレクションJavaのリフレクションを使用してコレクションの内容を変更します

私の質問:リフレクションを使用してこのコレクションのコンテンツを変更するにはどうすればよいですか?

+0

コレクションを(リフレクトで)取得し、そのメソッドを使用しますか? – Kayaman

+0

しかし、コレクションの要素の種類を知る方法はありますか? –

+0

いくつかの反射トリッキーでジェネリックタイプを取得できます。https://stackoverflow.com/questions/1901164/get-type-of-a-generic-parameter-in-java-with-reflection – Kayaman

答えて

0

[OK]をので、この記事では私をたくさん助け:Get type of a generic parameter in Java with reflection

しかし、私はまだので、ここで説明するコードの一部をいくつかproblemeを持っていた:

は、コレクション型のプロパティを持つ単純なクラスを言ってみましょう今

static class Bla { 
    public ArrayList<String> collection = new ArrayList<String>(); 
} 

反射でStringクラスを盗んする機能を参照してください。

public static void check(Object object) throws IllegalArgumentException, IllegalAccessException { 
    Class<?> objectClass = object.getClass(); 
    Field[] fields = objectClass.getFields(); 
    for (Field field : fields) { 
     Object prop = field.get(object); 
     if (prop instanceof ArrayList) { 
     Type genericType = field.getGenericType(); // To get the ArrayList<String> Type object 
     ParameterizedType pt = (ParameterizedType) genericType; // Cast to a ParameterizedType to 
                   // recover the type within <T> which 
                   // is String 
     Type[] atp = pt.getActualTypeArguments();// Then call the function to get the array of type 
               // argument (e.g.: <T>,<V,U>,...) 
     // Do something with this 
     } 
    } 
    } 

それだけです!

関連する問題