java注释参与编译吗,Java中的注释会导致编译时传递依赖吗?

A simple example where Ent.java uses annotations and is compiled with the necessary jar dependency after which Includer.java is compiled which in turn imports Ent.java.

Ent.java:

import javax.persistence.Entity;

import javax.persistence.Table;

@Entity

@Table(name="securities")

public class Ent {}

Includer.java:

public class Includer {

public void f() {

Ent s = new Ent();

}

}

Compiling this with...

javac -cp C:/apache-tomcat-7.0.59/lib/javax.persistence_2.1.0.v201304241213.jar Ent.java

javac Includer.java

...results in the following warning when compiling Includer.java:

.\Ent.class: warning: Cannot find annotation method 'name()' in type 'Table': class file for javax.persistence.Table not found

The same happens of course if we add more annotations but only annotations that take parameters seem to be causing this behaviour. Adding the jar dependency from the first compilation to the classpath when compiling Includer.java solves the problem but doesn't follow how I usually think dependencies are handled. Since I'm quite new to annotations, is it the expected behaviour that we need to add the dependencies of Ent.java to the classpath when compiling Includer.java (adding dependencies of dependencies so to speak...) or is this likely some sort of bug or some other kind of special case...? Compiler version javac 1.8.0_31 was used for this test.

解决方案

This seems related to this bug: JDK-6550655:

Compiler error when compiling a class alone that depends on another class, which has already been compiled and has a dependency on a class from persistence-api.jar

To answer your question, it is not required to place dependencies of the dependency class (Ent.java) to the classpath of the depending class (Includer.java). However, it seems javac also reads the annotations in the dependency class. According to the referenced bug, this used to cause a compilation failure (a com.sun.tools.javac.code.Symbol$CompletionFailure). As mentioned in the comments, this is modified to only throw a warning:

After the fix, the compiler will accept the program but issue

a warning. The rationale is that the missing annotation can cause

problems when running the program.

Also from the comments:

The compiler should not crash and this problem will be addressed first.

While it is desireable to allow the compilation to continue without the

annotation, I will have to investigate if it is allowable. For example,

the compiler cannot determine if the missing annotation has the

meta-annotation @Inherited.

This can cause problems for annotation processors.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值