打印使用反射列表(Printing a list using reflection)

2019-09-18 19:13发布

 public class Service{ 
       String serviceName;
      //setter and getter
  }

  public class Version{ 
       int VersionID;
      //setter and getter
  }

  public void test(Object list){

        //it shd print the obtained list

   }

列表<服务> list1的; //服务是一个Bean
列表<版>列表2; //版本是一个Bean
试验(列表1);
试验(列表2);

现在的测试方法SHD打印获得的列表- (即)如果该列表类型服务 ,那么服务名应使用其吸气剂进行打印。 如果列表类型为版本 VERSIONID应打印。
是否有可能实现这一目标而无需使用接口或抽象类?

Answer 1:

@danLeon具有最简单的想法至今(添加toString的类),假设你有机会获得ServiceVersion

我不知道为什么你在想反映的,但我能想到的唯一的事情就是你想要的东西,将与具有单属性的任何对象工作String吸气,然后你会做这样的事情(IMO疯狂,但它使用反射):

Class clazz = list.get(0).getClass();
Method[] methods = clazz.getDeclaredMethods();
Method onlyStringGetter = null;
for (Method method: methods) {
    String mName = method.getName();
    if (mName.matches("get\w+") {
        if (method.getReturnType().equals(String.class) {
            if (onlyStringGetter != null) thrown new RuntimeException("More than one String getter available");
            onlyStringGetter = method;
        }
    }
}
if (onlyStringGetter == null) throw new RuntimeException("No String getter found for class: " + clazz.getName());
List<String> strings = new ArrayList<String>();
for (Object singleStringAttribObj: list) {
    // some exception handling needed for below
    String result = (String)onlyStringGetter.invoke(singleStringAttribObj);
    strings.add(result);
}
System.out.println(strings);

我还没有编译或尝试过,但近似正确的。 当然一些额外的异常处理是必需的



Answer 2:

if(Object instanceof List) {
    List list = (List)Object ;

   for(int index=0; index < list.length();index++) {
       Object obj = list.get(index);

       if(obj instanceof Service) {
         //cast to service and print value or use reflection
           Service service= (Service)obj ;
           System.out.println(service.geServiceName());
       } else if(obj instanceof Version) {
          // cast to Version and print versionID  someting
          Version version = (Version)obj ;
          System.out.println(version.getVersionId());
     }
   }
}


Answer 3:

static public class Service {

    String serviceName;

    @Override
    public String toString() {
        return serviceName;
    }
}

static public class Version {

    String VersionID;

    @Override
    public String toString() {
        return VersionID;
    }
}

static public void test(List<?> list) {
    for (Object object : list) {
        System.out.println(object.toString());
    }
}


Answer 4:

public void test(Object list) {
    if(list instanceof List)
        test((List)list);
}

public void test(List<?> list) {
    if (!list.isEmpty()) {
        Object o = list.get(0);
        if (o instanceof Version) {
            @SuppressWarnings("unchecked")
            List<Version> lVersion = (List<Version>) list;
            for (Version v : lVersion) {
                System.out.println(v.getVersionID());
            }
        } else if (o instanceof Service) {
            @SuppressWarnings("unchecked")
            List<Service> lService = (List<Service>) list;
            for (Service s : lService) {
                System.out.println(s.getServiceName());
            }
        }
    }
}


文章来源: Printing a list using reflection