如何从注释处理器获取类代码作为字符串?

问题描述

我有一个基本的注释处理器

@SupportedAnnotationTypes("example.Annotation")
public class Processor extends AbstractProcessor {
    @Override
    public boolean process(Set<? extends TypeElement> annotations,RoundEnvironment roundEnv) {
        for (TypeElement annotation : annotations) {
            Set<? extends Element> elementsAnnotatedWith = roundEnv.getElementsAnnotatedWith(annotation);
            for (Element element : elementsAnnotatedWith) {
                TypeElement typeElement = (TypeElement) element;
                // Here,typeElement.getQualifiedname() is accessible,but not the code nor file path.
            }
        }
        return false;
    }
}

这个注解只能用在类上。我知道目标类未编译,因此无法进行反射访问,但我希望将类代码作为字符串以我自己的方式进行解析,而不是使用此 API。

有可能吗?我知道我可以获得限定名称,但在哪里查找文件

解决方法

import numpy as np,matplotlib.pyplot as plt # Solves linear system given by Tridiagonal Matrix # Helper for calculating cubic splines #@numba.njit(cache = True,fastmath = True,inline = 'always') def tri_diag_solve(A,B,C,F): n = B.size assert A.ndim == B.ndim == C.ndim == F.ndim == 1 and ( A.size == B.size == C.size == F.size == n ) #,(A.shape,B.shape,C.shape,F.shape) Bs,Fs = np.zeros_like(B),np.zeros_like(F) Bs[0],Fs[0] = B[0],F[0] for i in range(1,n): Bs[i] = B[i] - A[i] / Bs[i - 1] * C[i - 1] Fs[i] = F[i] - A[i] / Bs[i - 1] * Fs[i - 1] x = np.zeros_like(B) x[-1] = Fs[-1] / Bs[-1] for i in range(n - 2,-1,-1): x[i] = (Fs[i] - C[i] * x[i + 1]) / Bs[i] return x # Calculate cubic spline params #@numba.njit(cache = True,inline = 'always') def calc_spline_params(x,y): a = y h = np.diff(x) c = np.concatenate((np.zeros((1,),dtype = y.dtype),np.append(tri_diag_solve(h[:-1],(h[:-1] + h[1:]) * 2,h[1:],((a[2:] - a[1:-1]) / h[1:] - (a[1:-1] - a[:-2]) / h[:-1]) * 3),0))) d = np.diff(c) / (3 * h) b = (a[1:] - a[:-1]) / h + (2 * c[1:] + c[:-1]) / 3 * h return a[1:],b,c[1:],d # Spline value calculating function,given params and "x" #@numba.njit(cache = True,inline = 'always') def func_spline(x,ix,x0,a,c,d): dx = x - x0[1:][ix] return a[ix] + (b[ix] + (c[ix] + d[ix] * dx) * dx) * dx # Compute piece-wise spline function for "x" out of sorted "x0" points #@numba.njit([f'f{ii}[:](f{ii}[:],f{ii}[:],f{ii}[:])' for ii in (4,8)],# cache = True,inline = 'always') def piece_wise_spline(x,d): xsh = x.shape x = x.ravel() ix = np.searchsorted(x0[1 : -1],x) y = func_spline(x,d) y = y.reshape(xsh) return y def main(): x0 = np.array([4.0,5.638304088577984,6.785456961280076,4.0]) y0 = np.array([0.0,1.147152872702092,2.7854569612800755,4.423761049858059,3.2766081771559668]) t0 = np.arange(len(x0)).astype(np.float64) plt.plot(x0,y0) vs = [] for e in (x0,y0): a,d = calc_spline_params(t0,e) x = np.linspace(0,t0[-1],100) vs.append(piece_wise_spline(x,t0,d)) plt.plot(vs[0],vs[1]) plt.show() if __name__ == '__main__': main() 的源代码可以这样加载:

TypeElement

测试的 private String loadSource(TypeElement typeElement) throws IOException { final FileObject source = processingEnv.getFiler().getResource( StandardLocation.SOURCE_PATH,((PackageElement) typeElement.getEnclosingElement()).getQualifiedName(),typeElement.getSimpleName() + ".java"); try (Reader reader = source.openReader(true)) { final StringBuilder builder = new StringBuilder(); final char[] buf = new char[1024]; int read; while ((read = reader.read(buf)) != -1) { builder.append(buf,read); } return builder.toString(); } } jar 包含一个 Processor 文件,无需指定 META-INF/services/javax.annotation.processing.Processor 选项:

  • Maven:好的
  • Gradle:需要额外的配置,假设 -process 是源目录
src/main/java
  • 命令行:添加tasks.withType(JavaCompile) { configure(options) { options.setSourcepath(project.files('src/main/java')) } } 选项:

-sourcepath