【问题标题】:How to know which implementation will going to use while returning interface refrance如何知道返回接口引用时将使用哪个实现
【发布时间】:2015-06-19 15:54:19
【问题描述】:
@Override
public IEntity updateEntity(IEntity entity) {
    String entityType = null;
    try {
        entityType = getEntityType(entity);
        if (entity != null) {

            getHibernateTemplate().merge(entity);

        }
    } catch (Exception e) {
        ExceptionUtils.throwVSXException(entityType, e);
    }
    return entity;
}

公共接口 IEntity 扩展可序列化 {

ConnectivityEntity getConnectivityEntity();}

虽然IEntity是一个接口并且实现了这么多类,如何理解哪个实现的类会使用这个返回值

【问题讨论】:

    标签: java class interface return


    【解决方案1】:

    您可以使用instanceof 运算符并检查实现类。例如,如果 A 类和 B 类实现 IEntity 接口,则可以检查如下:

    @Override
    public IEntity updateEntity(IEntity entity) {
       String entityType = ""; // Returing null is bad
       ...... 
    
       if(entity instanceof A){
        entityType="A class"
       }
       else if(entity instanceof B){
        entityType= "B class"
       }
       return entityType
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-14
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      • 2012-09-05
      • 1970-01-01
      相关资源
      最近更新 更多