1 7 8 package javax.tools; 9 10 import java.io.File ; 11 import java.net.URL ; 12 import java.net.URLClassLoader ; 13 import java.net.MalformedURLException ; 14 15 23 public class ToolProvider { 24 25 private ToolProvider() {} 26 27 32 public static JavaCompiler getSystemJavaCompiler() { 33 if (Lazy.compilerClass == null) 34 return null; 35 try { 36 return Lazy.compilerClass.newInstance(); 37 } catch (Throwable e) { 38 return null; 39 } 40 } 41 42 51 public static ClassLoader getSystemToolClassLoader() { 52 if (Lazy.compilerClass == null) 53 return null; 54 return Lazy.compilerClass.getClassLoader(); 55 } 56 57 62 static class Lazy { 63 private static final String defaultJavaCompilerName 64 = "com.sun.tools.javac.api.JavacTool"; 65 private static final String [] defaultToolsLocation 66 = { "lib", "tools.jar" }; 67 static final Class <? extends JavaCompiler> compilerClass; 68 static { 69 Class <? extends JavaCompiler> c = null; 70 try { 71 c = findClass().asSubclass(JavaCompiler.class); 72 } catch (Throwable t) { 73 } 75 compilerClass = c; 76 } 77 78 private static Class <?> findClass() 79 throws MalformedURLException , ClassNotFoundException 80 { 81 try { 82 return enableAsserts(Class.forName(defaultJavaCompilerName, false, null)); 83 } catch (ClassNotFoundException e) { 84 } 86 File file = new File (System.getProperty("java.home")); 87 if (file.getName().equalsIgnoreCase("jre")) 88 file = file.getParentFile(); 89 for (String name : defaultToolsLocation) 90 file = new File (file, name); 91 URL [] urls = {file.toURI().toURL()}; 92 ClassLoader cl = URLClassLoader.newInstance(urls); 93 cl.setPackageAssertionStatus("com.sun.tools.javac", true); 94 return Class.forName(defaultJavaCompilerName, false, cl); 95 } 96 97 private static Class <?> enableAsserts(Class <?> cls) { 98 try { 99 ClassLoader loader = cls.getClassLoader(); 100 if (loader != null) 101 loader.setPackageAssertionStatus("com.sun.tools.javac", true); 102 } catch (SecurityException ex) { 103 } 105 return cls; 106 } 107 } 108 } 109 | Popular Tags |