有没有办法来检查一个字段是否存在一个泛型类?有没有办法检查Generic类是否存在字段?
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);
}
}
这可以用反射来完成,但我真的认为你应该重新考虑你的设计。也许你可以做一些基于接口的东西? – Keppil