简体   繁体   English

获取不同类型的变量

[英]Getting different types of variable

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. 我有一个Java形式,其中我声明了string类型的不同变量,而string数组类型的变量很少,而集合则很少。 Using getdeclaredfileds of reflection api , i am getting every field of class in my field array variable. 使用反射api的getdeclaredfileds,我将在字段数组变量中获取类的每个字段。 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; 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 . 现在, stringTypeMember包含String类型的所有类成员(字段)。

您能否获取所有变量并使用Field.getType()按类型过滤它们?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM