问题描述
这是不得已的问题。我在整个互联网上搜索了可能出问题的地方,但似乎没有任何效果。我创建了一个自定义批注,该批注应生成一个资源文件,其类如下:
@Target(METHOD)
@Retention(CLASS)
@Repeatable(Schedules.class)
public @interface Scheduled {
/**
* Specifies one or more minutes with in an hour.
*/
int[] minute() default {};
/**
* Specifies one or more hours within a day.
*/
int[] hour() default {};
/**
* Specifies one or more days in a month
*/
int[] date() default {};
/**
* Specifies one or more months within a year.
*/
int[] month() default {};
/**
* Specifies one or more days within a week.
*/
int[] dayOfWeek() default {};
}
和
@Target(METHOD)
@Retention(CLASS)
public @interface Schedules {
Scheduled[] value();
}
注释处理器的结构如下:
@SupportedAnnotationTypes({"files.application.Scheduled"})
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class ScheduledProcessor extends AbstractProcessor {
@Override
public synchronized void init(ProcessingEnvironment env) {
super.init(env);
}
@Override
public boolean process(Set<? extends TypeElement> annotations,RoundEnvironment roundEnv) {
...
}
public void buildFile(ArrayList<String> scheduledList) {
...
}
}
注释的测试类:
public class AnnotationTest {
private int age;
private String name;
@Scheduled
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return this.age;
}
@Scheduled(month= {7,8})
@Scheduled(date= {5,6})
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
我们使用ANT任务通过代码来完成许多任务,其中一个就是compile
。
<target name="-compile" depends="-pre-compile,-classpath-compile">
<mkdir dir="${build.bin}"/>
<javac
destdir="${build.bin}"
encoding="UTF-8"
includeAntRuntime="false"
debug="true"
debuglevel="${build.javac.debuglevel}"
source="${build.javac.source}"
target="${build.javac.target}"
>
<src path="${build.source}" />
<src path="${build.gen}" />
<classpath refid="classpath.compile" />
<compilerarg line="-processor files.application.ScheduledProcessor"/>
<compilerarg line="-s ${build.source}" />
</javac>
我当前的项目结构是:
core
src
annotsProject
Scheduled.java
Schedules.java
ScheduledProcessor.java
AnnotationTest.java
meta-inf
services
javax.annotation.processing.Processor
anttasks.xml
运行编译ANT任务时,成功调用了init(ProcessingEvironment env)
,但是从未调用过process(Set<? extends TypeElement> annotations,RoundEnvironment roundEnv)
。我尝试创建处理器和meta-inf文件夹的.jar文件,并将其添加到项目构建路径,但没有成功。我已经尝试从命令行使用javac
,但还是没有。也许我误解了何时应该调用process()
方法,或者我的文件夹结构不正确?任何帮助将不胜感激!
解决方法
发布问题后我发现了。我将AnnotationTest.java
移到了自己的项目testProj
中,并为testProj
的ivy.xml添加了core
的依赖项。我编译了core
,已成功完成,但未显示有关注释处理器的任何信息。然后,我使用单独的ANT
命令构建了其工件。然后,我编译了testProj
,它确实在注解处理器中显示了printMessage()
中的process()
。我检查了要创建的文件的输出位置,就在那里!我认为使用注释处理器的.jar
方法是正确的方向,但是对于我们的项目设置方式,我可能把它放在了错误的位置。我们使用的工件ANT
命令为我构建了.jar
并将其放置在正确的位置,以便testProj
可以看到它。发布我的答案以防万一。