为什么切换会导致无法解决错误?
我在包 A 中有一个枚举,它有一个静态转换器方法,我用它来为另一个包 B 中的一组特定类获取适当的枚举类型(另一个包中的每个类都有一个相应的枚举)。
现在,从第三个包 C(它不导入包 A,但导入包 B)中,我尝试打开枚举。
现在,当我使用 switch
检查枚举时,它会抱怨:
无法解析类型 nz.ac.waikato.jstar.jStar.OrderOperator。它是从必需的 .class 间接引用的 文件
但是,当我使用 if 语句时却没有。
谁能解释一下为什么 switch
会导致错误,而 if
却不会?
代码:
//Doesn't work
switch (connection.getType()) {
case LESS_THAN:
break;
case LESS_THAN_EQUALS:
break;
default:
break;
}
//Works Fine
if(connection.getType() == OrderingConnectionType.LESS_THAN) {
return -1;
} else if(connection.getType() == OrderingConnectionType.LESS_THAN_EQUALS) {
return 2;
}
引用bundle A的Enum静态方法(OrderOperator来自Bundle A):
public static OrderingConnectionType getType(Class<? extends OrderOperator> operatorType) {
for (OrderingConnectionType type : OrderingConnectionType.values()) {
if(type.operatorType.isAssignableFrom(operatorType)) return type;
}
throw new IllegalArgumentException("Unknown Operator type: " + operatorType);
}
I have an enum in package A which has a static converter method, which I use to get the appropriate enum type for a particular set of classes in another package B (each class in the other package has a corresponding enum).
Now, from a third package C, which does not import package A, but does import package B I'm trying to switch on the enum.
Now, when I use a switch
to check the enum, it complains:
The type nz.ac.waikato.jstar.jStar.OrderOperator cannot be resolved. It is indirectly referenced from required .class
files
However, when I use an if statement it doesn't.
Can anyone shed light as to why the switch
causes the error but the if
doesn't?
Code:
//Doesn't work
switch (connection.getType()) {
case LESS_THAN:
break;
case LESS_THAN_EQUALS:
break;
default:
break;
}
//Works Fine
if(connection.getType() == OrderingConnectionType.LESS_THAN) {
return -1;
} else if(connection.getType() == OrderingConnectionType.LESS_THAN_EQUALS) {
return 2;
}
Enum's static method that refers to bundle A (OrderOperator is from Bundle A):
public static OrderingConnectionType getType(Class<? extends OrderOperator> operatorType) {
for (OrderingConnectionType type : OrderingConnectionType.values()) {
if(type.operatorType.isAssignableFrom(operatorType)) return type;
}
throw new IllegalArgumentException("Unknown Operator type: " + operatorType);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
添加 OrderingConnectionType。为开关的情况添加前缀,它将起作用。
Add OrderingConnectionType. prefix to cases of the switch, it will work.
您应该给出精确的枚举类型进行比较。您是在
if 语句
中执行此操作,而不是在switch
中执行此操作。you should give exact enum type to compare.. you are doing this in
if statement
but not inswitch
.检查您的进口声明。 LESS_THAN 和 LESS_THAN_EQUALS 枚举值可能是从
nz.ac.waikato.jstar.jStar.OrderOperator
类型导入的,而不是您自己的OrderingConnectionType
类型。Check your import statement. The LESS_THAN and LESS_THAN_EQUALS enum values are probably being imported from the type
nz.ac.waikato.jstar.jStar.OrderOperator
rather than your ownOrderingConnectionType
.