相关疑难解决方法(0)

使用注释处理器替换代码

我正在尝试编写一个注释处理器来在类上插入方法和字段......而且文档非常稀疏.我没有走得太远,我不知道我是否正确接近它.

处理环境提供了一个Filer对象,该对象具有用于创建新源和类文件的方便方法.那些工作正常,但后来我试图弄清楚如何读取现有的源文件,它提供的只是"getResource".所以在我的处理器实现中我做到了:

@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    try {
        for (TypeElement te : annotations) {
            for (Element element : roundEnv.getElementsAnnotatedWith(te)) {
                FileObject in_file = processingEnv.getFiler().getResource(
                    StandardLocation.SOURCE_PATH, "",
                    element.asType().toString().replace(".", "/") + ".java");

                FileObject out_file = processingEnv.getFiler().getResource(
                    StandardLocation.SOURCE_OUTPUT, "",
                    element.asType().toString().replace(".", "/") + ".java");

                //if (out_file.getLastModified() >= in_file.getLastModified()) continue;

                CharSequence data = in_file.getCharContent(false);

                data = transform(data); // run the macro processor

                JavaFileObject out_file2 = processingEnv.getFiler().createSourceFile(
                    element.asType().toString(), element);
                Writer w = out_file2.openWriter();
                w.append(data);
                w.close();
            } …
Run Code Online (Sandbox Code Playgroud)

java code-generation annotation-processing

20
推荐指数
1
解决办法
1万
查看次数