當前位置: 首頁>>代碼示例>>Java>>正文


Java ToolProvider類代碼示例

本文整理匯總了Java中javax.tools.ToolProvider的典型用法代碼示例。如果您正苦於以下問題:Java ToolProvider類的具體用法?Java ToolProvider怎麽用?Java ToolProvider使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


ToolProvider類屬於javax.tools包,在下文中一共展示了ToolProvider類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: testNull

import javax.tools.ToolProvider; //導入依賴的package包/類
/**
 * Verify null is handled correctly.
 */
@Test
public void testNull() throws Exception {
    DocumentationTool tool = ToolProvider.getSystemDocumentationTool();
    try (StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null)) {
        File outDir = getOutDir();
        fm.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, Arrays.asList(outDir));
        Iterable<? extends JavaFileObject> files = Arrays.asList((JavaFileObject) null);
        try {
            DocumentationTask t = tool.getTask(null, fm, null, null, null, files);
            error("getTask succeeded, no exception thrown");
        } catch (NullPointerException e) {
            System.err.println("exception caught as expected: " + e);
        }
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:19,代碼來源:GetTask_FileObjectsTest.java

示例2: testDoclet

import javax.tools.ToolProvider; //導入依賴的package包/類
/**
 * Verify that an alternate doclet can be specified.
 *
 * There is no standard interface or superclass for a doclet;
 * the only requirement is that it provides static methods that
 * can be invoked via reflection. So, for now, the doclet is
 * specified as a class.
 * Because we cannot create and use a unique instance of the class,
 * we verify that the doclet has been called by having it record
 * (in a static field!) the comment from the last time it was invoked,
 * which is randomly generated each time the test is run.
 */
@Test
public void testDoclet() throws Exception {
    Random r = new Random();
    int key = r.nextInt();
    JavaFileObject srcFile = createSimpleJavaFileObject(
            "pkg/C",
            "package pkg; /** " + key + "*/ public class C { }");
    DocumentationTool tool = ToolProvider.getSystemDocumentationTool();
    try (StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null)) {
        File outDir = getOutDir();
        fm.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, Arrays.asList(outDir));
        Iterable<? extends JavaFileObject> files = Arrays.asList(srcFile);
        DocumentationTask t = tool.getTask(null, fm, null, TestDoclet.class, null, files);
        if (t.call()) {
            System.err.println("task succeeded");
            if (TestDoclet.lastCaller.equals(String.valueOf(key)))
                System.err.println("found expected key: " + key);
            else
                error("Expected key not found");
            checkFiles(outDir, Collections.<String>emptySet());
        } else {
            throw new Exception("task failed");
        }
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:38,代碼來源:GetTask_DocletClassTest.java

示例3: testStandardFileObject

import javax.tools.ToolProvider; //導入依賴的package包/類
/**
 * Verify that expected output files are written via the file manager,
 * for a source file read from the file system with StandardJavaFileManager.
 */
@Test
public void testStandardFileObject() throws Exception {
    File testSrc = new File(System.getProperty("test.src"));
    File srcFile = new File(testSrc, "pkg/C.java");
    DocumentationTool tool = ToolProvider.getSystemDocumentationTool();
    try (StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null)) {
        File outDir = getOutDir();
        fm.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, Arrays.asList(outDir));
        Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(srcFile);
        DocumentationTask t = tool.getTask(null, fm, null, null, null, files);
        if (t.call()) {
            System.err.println("task succeeded");
            checkFiles(outDir, standardExpectFiles);
        } else {
            throw new Exception("task failed");
        }
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:23,代碼來源:GetTask_FileObjectsTest.java

示例4: testNoIndex

import javax.tools.ToolProvider; //導入依賴的package包/類
/**
 * Verify that expected output files are written for given options.
 */
@Test
public void testNoIndex() throws Exception {
    JavaFileObject srcFile = createSimpleJavaFileObject();
    DocumentationTool tool = ToolProvider.getSystemDocumentationTool();
    try (StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null)) {
        File outDir = getOutDir();
        fm.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, Arrays.asList(outDir));
        Iterable<? extends JavaFileObject> files = Arrays.asList(srcFile);
        Iterable<String> options = Arrays.asList("-noindex");
        DocumentationTask t = tool.getTask(null, fm, null, null, options, files);
        if (t.call()) {
            System.err.println("task succeeded");
            Set<String> expectFiles = new TreeSet<String>(noIndexFiles);
            checkFiles(outDir, expectFiles);
        } else {
            error("task failed");
        }
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:23,代碼來源:GetTask_OptionsTest.java

示例5: testJavac

import javax.tools.ToolProvider; //導入依賴的package包/類
public void testJavac() throws Exception {
    final JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
    final StandardJavaFileManager fm = jc.getStandardFileManager(
            null,
            Locale.ENGLISH,
            Charset.forName("UTF-8"));  //NOI18N
    fm.setLocation(
            StandardLocation.CLASS_PATH,
            Collections.singleton(FileUtil.archiveOrDirForURL(mvCp.entries().get(0).getURL())));
    Iterable<JavaFileObject> res = fm.list(
            StandardLocation.CLASS_PATH,
            "", //NOI18N
            EnumSet.of(JavaFileObject.Kind.CLASS),
            true);
    assertEquals(3, StreamSupport.stream(res.spliterator(), false).count());
}
 
開發者ID:apache,項目名稱:incubator-netbeans,代碼行數:17,代碼來源:MRJARCachingFileManagerTest.java

示例6: compile

import javax.tools.ToolProvider; //導入依賴的package包/類
private void compile(String option, Path destDir, Path... files)
        throws IOException
{
    System.err.println("compile...");
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null)) {
        Iterable<? extends JavaFileObject> fileObjects =
            fm.getJavaFileObjectsFromPaths(Arrays.asList(files));

        List<String> options = new ArrayList<>();
        if (option != null) {
            options.add(option);
        }
        if (destDir != null) {
            options.add("-d");
            options.add(destDir.toString());
        }
        options.add("-cp");
        options.add(System.getProperty("test.classes", "."));

        JavaCompiler.CompilationTask task =
            compiler.getTask(null, fm, null, options, null, fileObjects);
        if (!task.call())
            throw new AssertionError("compilation failed");
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:27,代碼來源:PackageInfoTest.java

示例7: getLocation_ISA

import javax.tools.ToolProvider; //導入依賴的package包/類
@Test
public void getLocation_ISA(Path base) throws Exception {
    Path src1 = base.resolve("src1");
    tb.writeJavaFiles(src1.resolve("m1x"), "module m1x { }", "package a; class A { }");
    Path src2 = base.resolve("src2");
    tb.writeJavaFiles(src2.resolve("m2x").resolve("extra"), "module m2x { }", "package b; class B { }");
    Path modules = base.resolve("modules");
    tb.createDirectories(modules);

    String FS = File.separator;
    String PS = File.pathSeparator;
    JavaCompiler c = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = c.getStandardFileManager(null, null, null)) {
        fm.handleOption("--module-source-path",
                List.of(src1 + PS + src2 + FS + "*" + FS + "extra").iterator());

        try {
            Iterable<? extends Path> paths = fm.getLocationAsPaths(StandardLocation.MODULE_SOURCE_PATH);
            out.println("result: " + asList(paths));
            throw new Exception("expected IllegalStateException not thrown");
        } catch (IllegalStateException e) {
            out.println("Exception thrown, as expected: " + e);
        }

        // even if we can't do getLocation for the MODULE_SOURCE_PATH, we should be able
        // to do getLocation for the modules, which will additionally confirm the option
        // was effective as intended.
        Location locn1 = fm.getLocationForModule(StandardLocation.MODULE_SOURCE_PATH, "m1x");
        checkLocation(fm.getLocationAsPaths(locn1), List.of(src1.resolve("m1x")));
        Location locn2 = fm.getLocationForModule(StandardLocation.MODULE_SOURCE_PATH, "m2x");
        checkLocation(fm.getLocationAsPaths(locn2), List.of(src2.resolve("m2x").resolve("extra")));
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:34,代碼來源:ModuleSourcePathTest.java

示例8: compileTestClass

import javax.tools.ToolProvider; //導入依賴的package包/類
/**
 * Compiles the test class with bogus code into a .class file.
 * Unfortunately it's very tedious.
 * @param counter Unique test counter.
 * @param packageNameSuffix Package name suffix (e.g. ".suffix") for nesting, or "".
 * @return The resulting .class file and the location in jar it is supposed to go to.
 */
private static FileAndPath compileTestClass(long counter,
    String packageNameSuffix, String classNamePrefix) throws Exception {
  classNamePrefix = classNamePrefix + counter;
  String packageName = makePackageName(packageNameSuffix, counter);
  String javaPath = basePath + classNamePrefix + ".java";
  String classPath = basePath + classNamePrefix + ".class";
  PrintStream source = new PrintStream(javaPath);
  source.println("package " + packageName + ";");
  source.println("public class " + classNamePrefix
      + " { public static void main(String[] args) { } };");
  source.close();
  JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
  int result = jc.run(null, null, null, javaPath);
  assertEquals(0, result);
  File classFile = new File(classPath);
  assertTrue(classFile.exists());
  return new FileAndPath(packageName.replace('.', '/') + '/', classFile);
}
 
開發者ID:fengchen8086,項目名稱:ditb,代碼行數:26,代碼來源:TestClassFinder.java

示例9: parsePackage

import javax.tools.ToolProvider; //導入依賴的package包/類
@NonNull
private static String parsePackage(@NonNull final FileObject javaFile) {
    String pkg = "";    //NOI18N
    try {
        JavacTask jt = (JavacTask) ToolProvider.getSystemJavaCompiler().getTask(
                null,
                null,
                null,
                Collections.EMPTY_LIST,
                Collections.EMPTY_LIST,
                Collections.singleton(new JFO(javaFile)));
        final Iterator<? extends CompilationUnitTree> cus = jt.parse().iterator();
        if (cus.hasNext()) {
            pkg = Optional.ofNullable(cus.next().getPackage())
                .map((pt) -> pt.getPackageName())
                .map((xt) -> xt.toString())
                .orElse(pkg);
        }
    } catch (IOException ioe) {
        //TODO: Log & pass
    }
    return pkg;
}
 
開發者ID:apache,項目名稱:incubator-netbeans,代碼行數:24,代碼來源:DefaultSourceLevelQueryImpl.java

示例10: compileDependencyClass

import javax.tools.ToolProvider; //導入依賴的package包/類
@BeforeClass
public static void compileDependencyClass() throws IOException, ClassNotFoundException {
  JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
  Assume.assumeNotNull(javaCompiler);

  classes = temporaryFolder.newFolder("classes");;

  StandardJavaFileManager fileManager = javaCompiler.getStandardFileManager(null, Locale.ROOT, UTF_8);
  fileManager.setLocation(StandardLocation.CLASS_OUTPUT, ImmutableList.of(classes));

  SimpleJavaFileObject compilationUnit = new SimpleJavaFileObject(URI.create("FooTest.java"), Kind.SOURCE) {
    String fooTestSource = Resources.toString(Resources.getResource("com/dremio/exec/compile/FooTest.java"), UTF_8);
    @Override
    public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
      return fooTestSource;
    }
  };

  CompilationTask task = javaCompiler.getTask(null, fileManager, null, Collections.<String>emptyList(), null, ImmutableList.of(compilationUnit));
  assertTrue(task.call());
}
 
開發者ID:dremio,項目名稱:dremio-oss,代碼行數:22,代碼來源:TestClassCompilers.java

示例11: createGoldenJFM

import javax.tools.ToolProvider; //導入依賴的package包/類
/** Crates the default javac file managare tro have something to comare 
    * our file managers against
    */
   public static JavaFileManager createGoldenJFM( File[] classpath, File[] sourcpath ) throws IOException {

JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
       StandardJavaFileManager fm = jc.getStandardFileManager (null, null, null);

if ( classpath != null ) {
           fm.setLocation(StandardLocation.CLASS_PATH,Arrays.asList(classpath));
}

if ( sourcpath != null ) {
    fm.setLocation(StandardLocation.SOURCE_PATH,Arrays.asList(sourcpath));
}

return fm;
	
   }
 
開發者ID:apache,項目名稱:incubator-netbeans,代碼行數:20,代碼來源:FileManagerTest.java

示例12: parse

import javax.tools.ToolProvider; //導入依賴的package包/類
public static void parse(Path moduleInfoPath, ModuleClassVisitor moduleClassVisitor) throws IOException {
  JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  try(StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null)) {
    Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(moduleInfoPath);
    CompilationTask task = compiler.getTask(null, fileManager, null, null, null, compilationUnits);
    JavacTask javacTask = (JavacTask)task;
    Iterable<? extends CompilationUnitTree> units= javacTask.parse();
    CompilationUnitTree unit = units.iterator().next();

    ModuleHandler moduleHandler = new ModuleHandler(moduleClassVisitor);
    TreeVisitor<?,?> visitor = (TreeVisitor<?,?>)Proxy.newProxyInstance(TreeVisitor.class.getClassLoader(), new Class<?>[]{ TreeVisitor.class},
        (proxy, method, args) -> {
          ModuleHandler.METHOD_MAP
          .getOrDefault(method.getName(), (handler, node, v) -> { 
            throw new AssertionError("invalid node " + node.getClass());
          })
          .visit(moduleHandler, (Tree)args[0], (TreeVisitor<?,?>)proxy);
          return null;
        });

    unit.accept(visitor, null);
  }
}
 
開發者ID:forax,項目名稱:moduletools,代碼行數:24,代碼來源:JavacModuleParser.java

示例13: main

import javax.tools.ToolProvider; //導入依賴的package包/類
public static void main(String[] args) throws Exception {
    File testSrc = new File(System.getProperty("test.src"));
    File thisSrc = new File(testSrc, T6963934.class.getSimpleName() + ".java");
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null)) {
        JavacTask task = (JavacTask) compiler.getTask(null, fileManager, null, null, null,
                fileManager.getJavaFileObjects(thisSrc));
        CompilationUnitTree tree = task.parse().iterator().next();
        int count = 0;
        for (ImportTree importTree : tree.getImports()) {
            System.out.println(importTree);
            count++;
        }
        int expected = 7;
        if (count != expected)
            throw new Exception("unexpected number of imports found: " + count + ", expected: " + expected);
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:19,代碼來源:T6963934.java

示例14: loadBadClass

import javax.tools.ToolProvider; //導入依賴的package包/類
private static BadClassFile loadBadClass(String className) {
    // load the class, and save the thrown BadClassFile exception
    JavaCompiler c = ToolProvider.getSystemJavaCompiler();
    JavacTaskImpl task = (JavacTaskImpl) c.getTask(null, null, null,
            Arrays.asList("-classpath", classesdir.getPath()), null, null);
    Symtab syms = Symtab.instance(task.getContext());
    task.ensureEntered();
    BadClassFile badClassFile;
    try {
        com.sun.tools.javac.main.JavaCompiler.instance(task.getContext())
                .resolveIdent(syms.unnamedModule, className).complete();
    } catch (BadClassFile e) {
        return e;
    }
    return null;
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:17,代碼來源:BadConstantValue.java

示例15: compileJavaFiles

import javax.tools.ToolProvider; //導入依賴的package包/類
/**
 * 動態編譯java文件
 * @param files
 */
private void compileJavaFiles(List<File> files) {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

    //獲取java文件管理類
    StandardJavaFileManager manager = compiler.getStandardFileManager(null, null, null);
    //獲取java文件對象迭代器
    Iterable<? extends JavaFileObject> it = manager.getJavaFileObjectsFromFiles(files);
    //設置編譯參數
    ArrayList<String> ops = new ArrayList<>();
    ops.add("-Xlint:unchecked");
    //獲取編譯任務
    JavaCompiler.CompilationTask task = compiler.getTask(null, manager, null, ops, null, it);
    //執行編譯任務
    task.call();
}
 
開發者ID:itfsw,項目名稱:mybatis-generator-plugin,代碼行數:20,代碼來源:MyBatisGeneratorTool.java


注:本文中的javax.tools.ToolProvider類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。