java - 在 Java 中初始化泛型

标签 java initialization

假设我有一个名为 NodeList 的类,它有两个字段,名为 value (类型 Object)和 index (类型int)。 NodeList 实现了一个名为 Copiable 的接口(interface),并使用一个名为 copyNotSyncronized() 的方法。

我希望 copyNotSincronyzed()NodeList 版本能够识别 this.value 是否实现 Copiable 并且,如果发生这种情况:

  1. this.value 上使用 copyNotSincronyzed() 并...
  2. ...构建一个新的 NodeList 对象,该对象将 this.value.copyNotSincronyzed() 作为字段 value

我试图编写代码并淹没在红色下划线中。之后我知道了两件事:我的 Eclipse 真的讨厌我,而且我仍然需要了解如何在 Java 中使用泛型。

我犯了什么错误?

public class NodeList implements Copiable {

    int index;
    Object value;

public NodeList(Object value, int index){
[...]
}

NodeList copyNotSincronyzed(){
  NodeList copied;
  if(  onArray.findPositionsOfElement(this.value.getClass().getInterfaces() , this.getClass().getInterfaces()[0])[0] !=-1   )
     // aka if this.value implements the same interface of this class (aka Copiable)
     {
// Following line features three errors: 
   // Incorrect number of arguments for type Class<T>; it cannot be parameterized with arguments <T, Copiable>
   // T cannot be resolved to a type
   // Syntax error on token "implements", , expected
     Class<T implements Copiable> copiedObject = this.value;


     copiedObject=copiedObject.copyNotSincronyzed();
     copied = new NodeList( copiedObject , this.index );
     }
   else copied = new NodeList(this.value, this.index);

   }  

}

最佳答案

this.value 的类型为 Object 。而您正尝试将其放入类型 Class<T implements Copiable> 。编译器不知道如何执行此操作,因此您会收到编译错误。

为了进行此检查,您应该使用instanceof运算符,并与强制转换结合使用,如下所示:

if (this.value instanceof Copiable){ // check that the instance implements an interface
    Copiable asCopiable = (Copiable)this.value; // safely cast to the appropriate type
}

请注意,您的问题与泛型无关。

关于java - 在 Java 中初始化泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26346164/

相关文章:

JAVA 为每个数组索引设置键

java - Liferay 钩子(Hook),jsp 不能在 glassfish 上编译

c++ - 在 STL vector 数组中初始化类

java - 切片 ListView

java - Spark on YARN - saveAsTextFile() 方法创建大量空零件文件

c - gcc 不再允许空数组吗?

java - StringBuilder循环: Local variable may not have been initialized

c - 想知道此声明与代码中的注释相比有什么问题吗? - 初学者在这里

java - 如何让 jackson 在反序列化期间将所有类似 map 的节点转换到我的自定义类?