I have a java form in which i have declared different variables of type string , and few variables of type string array and few are collections. Using getdeclaredfileds of reflection api , i am getting every field of class in my field array variable. But i want to separate the string variables into one common array. array strings into other array and collection fields into other one.
eg: - String abc; String def; String[] lmn; String[] opq; Collection mno;
String abc; String def; String[] lmn; String[] opq; Collection mno;
Define a utility method:
public static Map<Class<?>, List<Field>> getFieldsByType(Field[] fields) {
Map<Class<?>, List<Field>> result = new HashMap<Class<?>, List<Field>>();
for (Field field:fields) {
List<Field> fieldList = result.get(field.getType());
if (fieldList == null) {
fieldList = new ArrayList<Field>();
result.put(field.getType(), fieldList);
}
fieldList.add(field);
}
return result;
}
It separates the fields by type and stores them in a map.
Example usage:
Map<Class<?>, List<Field>> map = getFieldsByType(MyClass.class.getDeclaredFields());
List<Field> stringTypeMembers = map.get(String.class);
Now stringTypeMember
contains all class members (fields) that are of type String
.
您能否获取所有变量并使用Field.getType()
按类型过滤它们?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.