有沒有辦法來檢查一個字段是否存在一個泛型類?有沒有辦法檢查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