gpt4 book ai didi

java - 使用接口(interface)模拟可扩展枚举

转载 作者:行者123 更新时间:2023-11-29 08:56:18 25 4
gpt4 key购买 nike

所以我在这里尝试了这个关于编写可扩展枚举的“Effective Java 2nd edition”练习。

不过,我遇到了一个非常奇怪的问题——我让每个枚举实例都实现了接口(interface)方法,并且在 Eclipse 中看起来都不错。但是当我尝试通过 maven 编译它时,它失败了,尽管 eclipse 之前根本没有抛出任何编译错误(我的 eclipse 和 maven 使用相同的 JDK:1.6.0_33-b05)。事实证明,我也必须在枚举内部(在所有枚举实例之外)重写接口(interface)方法[我将从现在开始将其称为方法 X] 以解决此问题!

这里有一个解释这个的示例:

接口(interface):

public interface IDay
{
public boolean isHoliday();
}

枚举:

public enum Day implements IDay
{
SATURDAY
{
@Override
public boolean isHoliday()
{
return true;
}
},
SUNDAY
{
@Override
public boolean isHoliday()
{
return true;
}
},
MONDAY
{
@Override
public boolean isHoliday()
{
return false;
}
};

// Method X: the project won't compile for me without this method!
public boolean isHoliday()
{
return false;
}

}

调用:

public class DayTester
{
public static void main(final String[] args)
{
// line Y: this line won't maven compile if I got rid of the method X
System.out.println("Sunday: " + Day.SUNDAY.isHoliday());
}
}

很奇怪,如果没有 'X' 方法,eclipse 是完全可以的,但是 Maven 编译会在 Y 行失败,说

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile) on project X: Compilation failure [ERROR] DayTester.java:[7,46] cannot find symbol [ERROR] symbol : method isHoliday() [ERROR] location: class Day

如果我有方法 X,我的 eclipse 保存操作会自动插入 @Override。删除方法 X 会在我的 eclipse 中抛出编译错误,这些错误会出现在我之前拥有的那些 Override 注释上。

这是我的问题:1. 为什么在这种情况下 maven 不编译,而 eclipse 编译?2.这里的Override annotation errors是什么意思?3. 方法 X 是否可以通过某种方式访问​​?我想了解什么?

最佳答案

@Override注解

@Override - Checks that the method is an override. Causes a compile error if the method is not found in one of the parent classes or implemented interface

eclipse 配置

Properties > Java Compiler > Compiler compliance level = 1.6

也在项目级别检查编译器合规性级别

Properties > Java Compiler > Errors/Warnings

@Override 注解在 Annotations 下,默认被忽略。

Maven 配置

将此属性添加到 pom.xml

<properties>
<maven.compiler.source>1.6</maven.compiler.source>
<maven.compiler.target>1.6</maven.compiler.target>
</properties>

这是由 maven-compile-plugin 发布的

note that at present the default source setting is 1.5 and the default target setting is 1.5, independently of the JDK you run Maven with. If you want to change these defaults, you should set source and target as described in Setting the -source and -target of the Java Compiler.

阅读更多

关于java - 使用接口(interface)模拟可扩展枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20151294/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com