假设我有一个名为 NodeList
的类,它有两个字段,名为 value
(类型 Object
)和 index
(类型int
)。 NodeList
实现了一个名为 Copiable
的接口(interface),并使用一个名为 copyNotSyncronized()
的方法。
我希望 copyNotSincronyzed()
的 NodeList
版本能够识别 this.value
是否实现 Copiable
并且,如果发生这种情况:
- 在
this.value
上使用copyNotSincronyzed()
并... - ...构建一个新的
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/