このメソッドは、クラスの各フィールドを表すClass.getDeclaredFieldsの配列を取得します。Fieldこれらをループして、 によって返される型を確認できますField.getType。Listタイプtoのフィールドのフィルタリングはより複雑です。これについては、この記事List<String>を参照してください。
Field必要なフィールドの最初の動的検索を行った後、パフォーマンスを向上させるために、関連するオブジェクトを追跡 (メモ化) する必要があります。
簡単な例を次に示します。
//for each field declared in User,
for (Field field : User.class.getDeclaredFields()) {
//get the static type of the field
Class<?> fieldType = field.getType();
//if it's String,
if (fieldType == String.class) {
// save/use field
}
//if it's String[],
else if (fieldType == String[].class) {
// save/use field
}
//if it's List or a subtype of List,
else if (List.class.isAssignableFrom(fieldType)) {
//get the type as generic
ParameterizedType fieldGenericType =
(ParameterizedType)field.getGenericType();
//get it's first type parameter
Class<?> fieldTypeParameterType =
(Class<?>)fieldGenericType.getActualTypeArguments()[0];
//if the type parameter is String,
if (fieldTypeParameterType == String.class) {
// save/use field
}
}
}
matchの==代わりに参照 equality() を使用したことに注意してください。isAssignableFromString.classString[].classStringfinal
編集:ネストされた s を見つけることについて少し気づきましたUserDefinedObject。それらを検索するために、上記の戦略に再帰を適用できます。