繁体   English   中英

有没有一种方法可以检查泛型类的字段是否存在?

[英]Is there a way to check if a field exists for a Generic class?

有没有一种方法可以检查泛型类的字段是否存在?

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);
    }

}

除了使用反射,我没有其他方法。 应该是这样的(未经测试):

try {
   Field field = entity.getClass().getField("street");
   if (field.getType().equals(String.class) {
      street = (String) field.get(entity);
   }
} catch (NoSuchFieldException ex) {
  /* ignore */
}

如果您可以控制类型层次结构,则可以使用getStreet()方法getStreet()类似HasStreet的接口,并让街道实体实现该接口。 那会更清洁:只需检查该接口是否已实现,然后进行强制转换并调用该方法。

如果可以减少E的不同选项,则可以使用instanceof检查类:

public abstract class AbstractEntity {
    public string name;
}

public class Person extends AbstractEntity {
    public String street;
    ...
}

public class Car extends AbstractEntity {

    ...
}

public abstract class Base<E extends AbstractEntity> {
    ...
    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
        if (entity instanceof Person) {
            Person p= (Person) entity;
            street=p.street;
        } else  if (entity instanceof Car) {
            //...
        }
        logger.trace("Entity name: {}", street);
    }

}

如果不是这种情况,则必须使用反射:

try {
   Field field = entity.getClass().getField("street");
   street = (String) field.get(entity);
} catch (NoSuchFieldException ex) {
  //This entity has no street field
}

不,您不可能访问在类方法内定义的局部变量。 编译器不会保留名称。

如果将属性/字段定义为类级别的属性,则可以按@Landei提及的方式访问它们。

您可以使用反射来检查该字段是否存在:

public void doSomething(E entity) {
    String street = "";
    Class<?> entityClass = entity.getClass();
    // getDeclaredField would allow to see non-public members
    Field streetField = entityClass.getField("street");
    // you should check the type of the filed here !
    logger.trace("Entity name: {}", streetField.get());
}

有关更多详细信息,请参见http://docs.oracle.com/javase/tutorial/reflect/index.html

但是,将泛型与反射结合使用对我来说似乎是一种气味,我建议您重新考虑您的设计,以确保没有其他方法!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM