Javac无法在具有公共枚举的静态嵌套类上编译注释

时间:2013-05-21 20:48:16

标签: java lombok

我遇到了以下javac编译失败,其中javac无法识别具有公共枚举的静态嵌套类上的注释。一旦我将枚举移出静态嵌套类,就解决了编译错误。有谁知道为什么javac失败了?这是一个java编译器错误吗?或者是否有我不知道的java细微差别?

以下是一个独立的测试用例。

无法编译:

package test;

import test.AnnotationBug.NestedClassWithEnum.ParticipantType;

import lombok.Data;
import lombok.NoArgsConstructor;

import com.googlecode.objectify.annotation.Embed;

public class AnnotationBug {

  ParticipantType type;

  @Embed
  @Data
  @NoArgsConstructor
  public static final class NestedClassNoEnum {
  }

  @Embed
  @Data
  @NoArgsConstructor
  public static final class NestedClassWithEnum {
    ParticipantType type;

    public enum ParticipantType {
      ORGANIZER,
      REGISTERED,
      WAIT_LISTED
    }
  }
}

编译输出:

$ javac -classpath /home/avaliani/projects/jars/objectify-4.0b2.jar:/home/avaliani/projects/jars/lombok.jar  test/AnnotationBug.java
test/AnnotationBug.java:20: error: cannot find symbol
  @Embed
   ^
  symbol:   class Embed
  location: class AnnotationBug
test/AnnotationBug.java:21: error: cannot find symbol
  @Data
   ^
  symbol:   class Data
  location: class AnnotationBug
test/AnnotationBug.java:22: error: cannot find symbol
  @NoArgsConstructor
   ^
  symbol:   class NoArgsConstructor
  location: class AnnotationBug

编译:

package test;

// import test.AnnotationBug.NestedClassWithEnum.ParticipantType;

import lombok.Data;
import lombok.NoArgsConstructor;

import com.googlecode.objectify.annotation.Embed;

public class AnnotationBug {

  ParticipantType type;

  @Embed
  @Data
  @NoArgsConstructor
  public static final class NestedClassNoEnum {
  }

  @Embed
  @Data
  @NoArgsConstructor
  public static final class NestedClassWithEnum {
    ParticipantType type;

  }

  public enum ParticipantType {
    ORGANIZER,
    REGISTERED,
    WAIT_LISTED
  }
}

编译没有错误:

$ javac -classpath /home/avaliani/projects/jars/objectify-4.0b2.jar:/home/avaliani/projects/jars/lombok.jar  test/AnnotationBug.java

要指出的事情:

1)注意编译失败的行号。解析NestedClassNoEnum的注释没有问题。

2)Java版本:

$ java -version
java version "1.7.0_21"
OpenJDK Runtime Environment (IcedTea 2.3.9) (7u21-2.3.9-0ubuntu0.12.10.1)
OpenJDK 64-Bit Server VM (build 23.7-b01, mixed mode)

1 个答案:

答案 0 :(得分:11)

如果你删除静态类的导入,代码编译得很好,请看下面的代码[注意:我没有使用@Embed注释,因为我没有jar,但它不会有任何区别]:

//import NestedClassWithEnum.ParticipantType;
import lombok.Data;
import lombok.NoArgsConstructor;


public class AnnotationBug {

    NestedClassWithEnum.ParticipantType type;


    @Data
    @NoArgsConstructor
    public static final class NestedClassNoEnum {
    }


    @Data
    @NoArgsConstructor
    public static final class NestedClassWithEnum {
        ParticipantType type;

        public enum ParticipantType {
            ORGANIZER,
            REGISTERED,
            WAIT_LISTED
        }
    }
}

原因似乎与列和静态类的类加载有关。 Enums are eagerly loaded懒惰地加载静态类。因此,java可能会尝试在编译时自行停止,但这是猜测。

编辑: 根据与保罗的讨论,上面的猜测是不正确的。