Dim*_*ele 1 java generics field
有没有办法检查泛型类是否存在字段?
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);
}
}
Run Code Online (Sandbox Code Playgroud)
除了使用反射,我看不到其他方法。应该是这样的(未测试):
try {
Field field = entity.getClass().getField("street");
if (field.getType().equals(String.class) {
street = (String) field.get(entity);
}
} catch (NoSuchFieldException ex) {
/* ignore */
}
Run Code Online (Sandbox Code Playgroud)
如果您可以控制类型层次结构,您可以HasStreet使用getStreet()方法创建一个接口,并让带有街道的实体实现它。那会更简洁:只需检查该接口是否已实现,然后转换并调用该方法。