简体   繁体   English

为什么在使用通配符调用Enum.valueOf()时出现绑定不匹配错误

[英]Why do I get bound mismatch error wen calling Enum.valueOf() using a wildcard

I am trying to call the Enum<E> class's static method valueOf() but I received a compile error. 我正在尝试调用Enum<E>类的静态方法valueOf()但收到编译错误。 Please look at the code snippet below. 请查看下面的代码段。

public void hello(Class<? extends Enum<?>> q){  
    Object o= Enum.valueOf(q,"hello");      
}

IntelliJ IDEA complies the following code just fine, but Eclipse gives a compile error: IntelliJ IDEA可以很好地编译以下代码,但是Eclipse出现编译错误:

在此处输入图片说明

I don't know IntelliJ's workings, but I can tell you the reason why it doesn't compile. 我不知道IntelliJ的工作原理,但是我可以告诉您它无法编译的原因。

The method defined in the class Enum<T extends Enum<T>> 在类Enum<T extends Enum<T>>定义的方法Enum<T extends Enum<T>>

public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name)

has a first argument that is the class of a type T which is defined by T extends Enum<T> . 具有是类的类型的第一个参数T其通过定义T extends Enum<T> That is, it extends an enumeration type with the same generic type as itself. 也就是说,它使用与自身相同的通用类型扩展了枚举类型。

When you call the method with the first argument as 当您使用第一个参数调用方法时

Class<? extends Enum<?>>

you are not specifying that the two ? 您没有指定两个? are in fact the same type, as required. 实际上是根据需要的相同类型。 This throws the mismatch error. 这将引发不匹配错误。

What you can do with your method is turn it generic: 您可以使用您的方法做的就是使其通用:

public static <E extends Enum<?>> void hello(Class<E> q)

but as you can imagine, this will still not compile because ? 但是,您可以想象,这仍然不会编译,因为? is not necessarily E . 不一定是E So you need to spell it out: 因此,您需要说明一下:

public static <E extends Enum<E>> void hello(Class<E> q)

and this will compile. 这将编译。

Edit: another way to think about it 编辑:另一种思考方式

You could think of fixing your method signature 您可以考虑修复方法签名

public void hello(Class<? extends Enum<?>> q)

by changing it to 通过将其更改为

public void hello(Class<E extends Enum<E>> q)

just to specify that the two wildcards are the same. 只是指定两个通配符相同。 The concept is right, but the syntax is not legal. 这个概念是正确的,但是语法不合法。 You must define what E is (either by making your method generic or your class). 您必须定义E是什么(通过使方法通用或使类成为类)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM