使用反射打印列表

时间:2012-06-29 14:19:21

标签: java list reflection

 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

   }
  

列表与LT;服务与GT;列表1; //服务是一个豆子        列表与LT;版本>列表2; //版本是一个Bean
       试验(list1的);
       试验(列表2);

现在测试方法shd打印获得的列表 - (即)如果列表的类型为 Service ,则应使用其getter打印serviceName。如果列表类型为版本,则应打印版本ID 是否可以在不使用Interface或抽象类的情况下实现这一目标?

4 个答案:

答案 0 :(得分:0)

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());
     }
   }
}

答案 1 :(得分:0)

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());
            }
        }
    }
}

答案 2 :(得分:0)

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());
    }
}

答案 3 :(得分:0)

@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);

我没有编译或尝试,但这是大致正确的。肯定需要一些额外的异常处理