【发布时间】:2014-02-21 08:33:39
【问题描述】:
有没有办法检查通用类的字段是否存在?
public class Person {
public String name;
public String street;
...
}
public class Car {
public String name;
...
}
public abstract class Base<E> {
...
public void doSomething(E entity) {
String street = "";
//Check if the generic entity has a "street" or not.
// If a Person arrives: then the real street should appear
// If a Car arrives: then an empty string would be needed
logger.trace("Entity name: {}", street);
}
}
【问题讨论】:
-
这可以通过反射来完成,但我真的认为你应该重新考虑你的设计。也许你可以基于接口做一些事情?