代码之家  ›  专栏  ›  技术社区  ›  Tyvain

Java泛型类型在这种情况下不起作用

  •  4
  • Tyvain  · 技术社区  · 6 年前

    // display line numbers from a file 
    display(getLineNumber(myFile));
    
    // display users from DB
    display(getUsersName(myDBRepository));
    

    等。。。

    myInformationElements.stream().forEach(e -> display(e.getValue());
    

    以下是我目前为止的情况(不工作):

    public interface InformationElement {
        public <T> String getValue (T param);
    }
    
    
    public class NbFileLineInformationElement implements InformationElement{
        @Override
        public <File> String getValue(File param) {
              return *same code as in getLineNumber(myFile)*;
        }
    }
    
    public class UserInformationElement implements InformationElement{
          @Override
          public <UserRepository> String getValue(UserRepository param) {
             return *same code as in getUsersName(myDBRepository)*;
       }
    }
    
    1. 在这里,我的泛型类型不起作用:文件没有重新定义为java.io.File (我的jpa存储库也是如此)我做错了什么?
    1 回复  |  直到 6 年前
        1
  •  3
  •   rgettman    6 年前
    1. 您已经定义了类型参数 File UserRepository 在类名后面 Object 方法。

    2. 这不是最佳做法。在实现泛型方法时,这些方法必须保持泛型,并且至少在边界方面具有同样大的开放性。为了以后能够限制类型参数的含义,请在类/接口上定义它,并让子类用类型参数提供它对特定实现的含义。

    InformationElement 的类型参数,并在子类中提供类型参数。这些方法不再是泛型的,但它们确实使用在接口/类上定义的类型参数。

    interface InformationElement<T> {
        public String getValue (T param);
    }
    
    class NbFileLineInformationElement implements InformationElement<File>{
        @Override
        public String getValue(File param) {
              return /*same code as in getLineNumber(myFile)*/;
        }
    }
    
    class UserInformationElement implements InformationElement<UserRepository>{
          @Override
          public String getValue(UserRepository param) {
             return /*same code as in getUsersName(myDBRepository)*/;
       }
    }