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

标签 java maven enums

所以我在这里尝试了这个关于编写可扩展枚举的“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/

相关文章:

java - 如何暂停和重新启动自动 ejb

java - 递归:为什么我会出错?

java - 如何使用 Jersey 缓存响应?

java - 打开移位 : maven compiler error : Base64 can not find the symbol

iphone - iOS 6.1 和 Xcode 4.6,枚举警告 UIView 动画曲线 EaseOut

eclipse - Eclipse Kepler for Omnifaces 上的自动代码完成 o :importConstants

java - 如何从 SubnodeConfiguration 中检索 xml 属性?

java - 使用 Spring MVC 应用程序(没有 web.xml)部署的简单 HelloWorld 给出 404 错误

java - Maven 从中央存储库下载

c# - 如何在 C# 中为枚举重载运算符?