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
}
列表列表1; //服务是一个Bean
列表列表2; //版本是一个Bean
测试(列表1);
测试(列表2);
现在测试方法 shd 打印获得的列表 - (即)如果列表是类型Service,那么 serviceName 应该使用它的 getter 来打印。如果列表类型是Version应该打印版本ID。
是否可以在不使用接口或抽象类的情况下实现这一目标?
@danLeon 到目前为止有最简单的想法(添加toString
到课程),假设您有权访问Service
and Version
.
我不确定你为什么要考虑反射,但我唯一能想到的是你想要一些可以与任何具有单一属性的对象一起使用的东西String
getter,然后你会做这样的事情(我认为这很疯狂,但它使用反射):
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);
我没有编译或尝试过,但这大约是正确的。肯定需要一些额外的异常处理
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)