2014-02-19 173 views
1

我想要实现从Apache的共享BeanUtils的以下接口:为什么这个@Override不正确?

public interface Converter { 
    // Convert the specified input object into an output object of the specified type 
    <T> T convert(java.lang.Class<T> tClass, java.lang.Object o); 
} 

我实施应采取枚举的子类,String对象转换为指定类型的枚举。我试图使用以下声明:

class EnumConverter implements Converter { 
    @Override 
    public Enum convert(Class<Enum> tClass, Object o) { 
     ... 
    } 
} 

但编译器不同意我。它输出:

error: EnumConverter is not abstract and does not override abstract method convert(Class,Object) in Converter

error: name clash: convert(Class,Object) in EnumConverter and convert(Class,Object) in Converter have the same erasure, yet neither overrides the other

error: method does not override or implement a method from a supertype

我的实现有什么问题?

UPD。请仔细阅读该问题。我无法更改它在Apache Commons BeanUtils库中的Converter接口。

+0

你需要让你的接口一般为好。 –

+0

@DaveNewton“我想从Apache Commons BeanUtils实现以下接口”。它是我无法更改的第三方库。 –

回答

3

你在EnumConverterconvert方法不是一般的像Converterconvert方法是通用的。如果实现的方法定义了它自己的类型参数,那么重写方法也必须这样做。

但是,看起来您需要泛型类型参数为Enum。如果是这样,那么接口Converter必须是通用的,而不是方法。 convert方法将引用它的接口的泛型类型参数,而不是定义它自己的。

interface Converter<T> { 
    // Convert the specified input object into an output object of the specified type 
    T convert(java.lang.Class<T> tClass, java.lang.Object o); 
} 

然后,您可以在实现接口时指定Enum

class EnumConverter implements Converter<Enum>{ 
    @Override 
    public Enum convert(Class<Enum> tClass, Object o) { 
     ... 
    } 
} 

如果你不能改变的接口,那么你就必须实施用相同的泛型方法泛型方法。您不能添加任何边界,例如<T extends Enum<T>>

class EnumConverter implements Converter{ 
    @Override 
    public <T> T convert(Class<T> tClass, Object o) { 
     ... 
    } 
} 

如果你想让它仅枚举工作,那么你就必须在运行时执行它:

if (!Enum.class.isAssignableFrom(tClass)) 
    throw new IllegalArgumentException("Class must specify an Enum!"); 
+0

您能否为我的情况编写正确的类定义(不需要更改Converter界面)? –

+0

我无法更改Converter界面。 –

+0

太好了。感谢您的详细解答。 –

相关问题