如何用泛型参数覆盖具有对象参数的方法?

Jon*_*nas 2 java generics parameters type-erasure

我想重写一个具有类型参数的方法Object

public void setValue(Object value) {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

并使该参数具有泛型类型T

@Override
public void setValue(T value) {
    super.setValue(value);
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能在Java中做到这一点?

在 Eclipse 中我收到以下错误:

Multiple markers at this line
- The type parameter T is hiding the type T
- Name clash: The method setValue(T) of type TextField<T> has the 
 same erasure as setValue(Object) of type JFormattedTextField but does not 
 override it
- The method setValue(T) of type TextField<T> must override or 
 implement a supertype method
Run Code Online (Sandbox Code Playgroud)

mil*_*ose 5

您不能使重写方法接受比它所重写的方法更窄的类型。

\n\n

如果可以的话,以下是可能的:

\n\n
class A {\n    public setValue(Object o) {\xe2\x80\xa6}\n}\n\nclass B<T> extends A {\n    @Override\n    public setValue(T o) {\xe2\x80\xa6};\n}\n\nA a = new B<String>(); // this is valid\na.setValue(new Integer(123)); // this line would compile, but make no sense at runtime \n
Run Code Online (Sandbox Code Playgroud)\n