Java编译时类解析

时间:2012-03-21 20:15:16

标签: java classloader

如何在Java编译时获取特定标识符的类引用/ TypeElement?

假设我有以下源文件,并且我想获得对Pixel类的引用,以便我可以获得其成员字段的列表。

package com.foo.bar;
class Test {
    class Pixel {
        int x,y,r,g,b;
    }
    Pixel saturate(Pixel p, int value) {...}
}

Pixel类定义可以嵌套在Test类中,也可以包含在源不可​​用的其他包中。

我正在使用javax.tools API来编译源文件,我定义了访问者方法,因此我可以查看每个函数的参数。可以使用VariableTree var : node.getParameters()迭代函数的参数,但var.getType()的类型信息仅触发visitIdentifier类名称。此标识符只是简单名称Pixel,而不是完全限定的com.foo.bar.Pixel

我需要一种方法将此标识符转换为Pixel.classTypeElement以定义Pixel类,或转换为完全限定的com.foo.bar.Pixel字符串所以我可以在上面使用ClassLoader。

粗略的方法是记录所有类定义,然后尝试进行编译时类型查找,但这不适用于外部定义的类。

2 个答案:

答案 0 :(得分:0)

据我所知,var.getType().toString()会返回完全限定的类名。不幸的是我现在无法检查它,但请亲自尝试一下。

是的,我知道,除了日志记录之外,使用toString()是一种非常糟糕的样式,但似乎它们没有给我们其他选择。

答案 1 :(得分:0)

我最终创建了自己的类查找工具。对于那些感兴趣的人,我会在这里加入。

使用要包含在搜索中的每个源文件的路径名称来调用它:

  public void populateClassDefinitions(String path) {
    Iterable<? extends JavaFileObject> files = fileManager.getJavaFileObjects(path);
    CompilationTask task =
        compiler.getTask(null, fileManager, diagnosticsCollector, null, null, files);
    final JavacTask javacTask = (JavacTask) task;
    parseResult = null;
    try {
      parseResult = javacTask.parse();
    } catch (IOException e) {
      e.printStackTrace();
      return;
    }
    for (CompilationUnitTree tree : parseResult) {
      tree.accept(new TreeScanner<Void, Void>() {
        @Override
        public Void visitCompilationUnit(CompilationUnitTree node, Void p) {
          currentPackage = "";
          ExpressionTree packageName = node.getPackageName();
          if (packageName != null) {
            String packageNameString = String.valueOf(packageName);
            if (packageNameString.length() > 0) {
              currentPackage = packageNameString;
            }
          }
          TreeScanner<Void, String> visitor = new TreeScanner<Void, String>() {
            @Override
            public Void visitClass(ClassTree node, String packagePrefix) {
              if (classDefinitions.get(currentPackage) == null) {
                classDefinitions.put(currentPackage, new HashMap<String, ClassTree>());
              }
              classDefinitions.get(currentPackage).put(packagePrefix + node.getSimpleName(), node);
              return super.visitClass(node, packagePrefix + node.getSimpleName() + ".");
            }
          };
          for (Tree decls : node.getTypeDecls()) {
            decls.accept(visitor, "");
          }
          return super.visitCompilationUnit(node, p);
        }
      }, null);
    }
  }

调用此方法搜索课程。

  /**
   * Lookup the definition of a class.
   * 
   * Lookup order: 1. Search in the current file: within the current class scope upwards to the
   * root. 2. Search laterally across files with the same package value for implicitly included
   * classes. 3. Check all import statements.
   * 
   * @param pack
   *          Current package ex "edu.illinois.crhc"
   * @param scope
   *          Current scope ex "Test.InnerClass"
   * @param identifier
   *          The partial class name to search for
   * @return ClassTree the definition of this class if found
   */
  ClassLookup lookupClass(CompilationUnitTree packTree, String scope, String identifier) {
    dumpClassTable();
    String pack = packTree.getPackageName().toString();
    System.out.println("Looking for class " + pack + " - " + scope + " - " + identifier);
    // Search nested scope and within same package
    HashMap<String, ClassTree> packClasses = classDefinitions.get(pack);
    if (packClasses != null) {
      String[] scopeWalk = scope.split("\\.");
      for (int i = scopeWalk.length; i >= 0; i--) {
        StringBuilder scopeTest = new StringBuilder();
        for (int j = 0; j < i; j++) {
          scopeTest.append(scopeWalk[j] + ".");
        }
        scopeTest.append(identifier);
        System.out.println("Testing scope " + pack + " - " + scopeTest.toString());
        if (packClasses.containsKey(scopeTest.toString())) {
          return new ClassLookup(packClasses.get(scopeTest.toString()), pack.replace(".", "/")
              + "/" + scopeTest.toString().replace(".", "$"));
        }
      }
    }
    /*
     * Check if fully-qualified identifier (foo.bar.Widget) is used. This needs to search all
     * combinations of package and class nesting.
     */
    StringBuilder packTest = new StringBuilder();
    String[] qualifiedName = identifier.split("\\.");
    for (int i = 0; i < qualifiedName.length - 1; i++) {
      packTest.append(qualifiedName[i]);
      if (i != qualifiedName.length - 2) {
        packTest.append(".");
      }
    }
    String clazz = qualifiedName[qualifiedName.length - 1];
    System.out.println("Testing absolute identifier: " + packTest.toString() + " " + clazz);
    if (classDefinitions.containsKey(packTest.toString())) {
      HashMap<String, ClassTree> foundPack = classDefinitions.get(packTest.toString());
      if (foundPack.containsKey(clazz)) {
        return new ClassLookup(foundPack.get(clazz), packTest.toString().replace(".", "/") + "/"
            + clazz.replace(".", "$"));
      }
    }

    /*
     * Search import statements. Last identifier segment must be class name. Search all of the
     * packages for the identifier by splitting off the class name. a.b.c.Tree Tree.Branch
     * Tree.Branch.Leaf
     */
    for (ImportTree imp : currentPackTree.getImports()) {
      pack = imp.getQualifiedIdentifier().toString();
      System.out.println(pack);
      String[] importName = pack.split("\\.");
      // Split off class name.
      // TODO: (edge case) no package
      StringBuilder importTest = new StringBuilder();
      for (int i = 0; i < importName.length - 1; i++) {
        importTest.append(importName[i]);
        if (i != importName.length - 2) {
          importTest.append(".");
        }
      }
      // See if the last import segment is * or matches the first segment of the identifier.

      System.out.println("Testing globally " + importTest.toString() + " - " + identifier);
      if (classDefinitions.containsKey(importTest.toString())) {
        HashMap<String, ClassTree> foundPack = classDefinitions.get(importTest.toString());
        String[] identifierParts = identifier.split(".");
        String importClass = importName[importName.length-1];
        if (importClass.equals("*") || identifierParts[0].equals(importClass)) {
          if (foundPack.containsKey(identifier)) {
            return new ClassLookup(foundPack.get(identifier), importTest.toString().replace(".", "/")
                + "/" + identifier.replace(".", "$"));
          }
        }
      }
    }

    return null;
  }