import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.List;
import javax.tools.JavaCompiler;
import javax.tools.SimpleJavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import javax.tools.JavaCompiler.CompilationTask;
/**
* @author YuFa
*
*/
publicclass CompilerTest {
publicstaticvoid main(String[] args) throws Exception {
String source = "public class Main {" +
"public static void main(String[] args) {" +
"System.out.println(\"Hello World!\");" +
"} " +
"}";
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
StringSourceJavaObject sourceObject = new CompilerTest.StringSourceJavaObject("Main", source);
List<StringSourceJavaObject> fileObjects = Arrays.asList(sourceObject);
CompilationTask task = compiler.getTask(null, fileManager, null, null, null, fileObjects);
boolean result = task.call();
if (result) {
System.out.println("Compile succeeded!");
} else {
System.out.println("Compile failed!");
}
}
staticclass StringSourceJavaObject extends SimpleJavaFileObject {
private String content = null;
public StringSourceJavaObject(String name, String content) throws URISyntaxException {
super(URI.create("string:///" + name.replace('.','/') + Kind.SOURCE.extension), Kind.SOURCE);
this.content = content;
}
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
return content;
}
}
}
注意编译上面代码是需要JRE6的,因为JavaCompiler等类都是在JDK6中提供的。当我运行上面代码的时候,结果却抛出了null pointer exception. 问题出在如下这行代码...
ToolProvider.getSystemJavaCompiler()返回的是NULL,因此在调用compiler.getStandardFileManager(null, null, null)的时候抛出了null pointer exception.
为啥会这样呢?查看了下ToolProvider的源代码,发现如下这么一段....
private static final String[] defaultToolsLocation = { "lib", "tools.jar" };privatestatic Class<?> findClass()
throws MalformedURLException, ClassNotFoundException
{
try {
return enableAsserts(Class.forName(defaultJavaCompilerName, false, null));
} catch (ClassNotFoundException e) {
// ignored, try looking else where
}
File file = new File(System.getProperty("java.home"));
if (file.getName().equalsIgnoreCase("jre"))
file = file.getParentFile();
for (String name : defaultToolsLocation)
file = new File(file, name);
URL[] urls = {file.toURI().toURL()};
ClassLoader cl = URLClassLoader.newInstance(urls);
cl.setPackageAssertionStatus("com.sun.tools.javac", true);
return Class.forName(defaultJavaCompilerName, false, cl);
}
我已经设置了JAVA_HOME环境变量,指向了我的JRE安装目录C:\Java\jre6, 注意查找文件的代码...
for (String name : defaultToolsLocation)
file = new File(file, name);
也就是说会查找目录C:\Java\jre6\lib\tools.jar
但是注意的是tools.jar并不在jre中,而是在jdk安装目录下,因此我手动把这个jar文件从jdk目录下拷贝到了jre目录下,再次运行上面的代码就没有问题了!同时注意到在代码工程目录下生成了一个名为Main.class的文件,这个确实说明了动态类Main已经编译成功了!
相关推荐
return;} else { GetTop(S,&ch); if(ch=='(') Pop(S,&ch); else { printf("\n对应的左右()括号不同类!"); return;} } break; case ']': if(IsEmpty(S)) { printf("\n右括号]多余!"); return;} else...
InitPHP采用了分层体系架构,在MVC模式基础上进行延伸!详细的API文档和使用Zend studio开发代码提示,让您开发更加速度!我们对每一个框架函数进行了思考,用简单...5. ajax_return 添加json和xml的HTTP Content-type
Read/convert/return argument lists in various formats
runsh - return Linux or Windows command result,ex:!runsh svn info9.!addfilewatch - add a file watching dog,max:100,ex:!addfilewatch a.log10.!getwatchstring - return file watch string,ex:!...
类似于赶集网的租房的多条件查询,查询代码如下: public List<FinancialProduct> select(FinancialProduct f) throws Exception { Set<FinancialProduct> sets=new HashSet();... return list; }
$("[href$='upload']").click(function(event){ ... return false; }; $.getJSON("/index.php/rest/users/getUserInfo/"+ username, function(data){ if(data.up_type != 1 && data.up_type !=2) {
= null && info.isConnected()); 6. } public static boolean isNetworkAvailable(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService( Context.CONNECTIVITY_...
= null) { this.cookie = this.Request.Cookies["iofficelogin"]; this.txtloginid.Text = this.cookie.Values["loginid"]; int num = this.dropBranch.Items.Count - 1; this.i = 0; while (this.i ) { if ...
方法一:使用while循环来计算 n = int(input()) jie = 1 sum = 0 i = 1 while n >= i: jie = jie * i ... return n*jie(n-1) n = int(input()) sum = 0 if n < 1> 40: print(请重新输入数据) else:
结果或默认C#6 将支持空值传播( )。 Result.OrDefault 是 C#6 之前的简单空值传播。 您知道“在发票视图中显示员工姓名”之类的要求吗...= null ) { return SelectedItem . Invoice . Employee . Name . ToString ();
VB编程获取汉字首字母并返回大写字母代码
Ticker.hasEventListener=null,Ticker._listeners=null,createjs.EventDispatcher.initialize(Ticker),Ticker._addEventListener=Ticker.addEventListener,Ticker.addEventListener=function(){return!Ticker._...
this.Container_initialize(),this.timeline=new createjs.Timeline(null,e,f),this._managed={}},b.isVisible=function(){return!!(this.visible&&this;.alpha>0&&0!=this.scaleX&&0!=this.scaleY)},b.Container_...
后台实现代码如下: ... { string sqlString = "select count(*) from Users where name='"+name+"' and pass='"+pass+"'";...=null && obj.ToString()!="0") return true; else return false; }
//图像打开失败时img也不为null,用Empty()判断 if (img.Empty()) { MessageBox.Show($"获取图像有误:{openFileDlg.FileName}", "提示"); return; } Cv2.ImShow("Image", img);//显示图像 Cv2.WaitKey(0);/...
function disposeDatePicker(){var src=null; if(window.event){src=event.srcElement||event.target;} if($dp!=undefined&&$dp.obj!=undefined&&$dp.style.display!='none'&&src!=$dp.obj.eCont) {var d=$dp....
return null; } // 判断Key是否为16位 if (sKey.length() != 16) { System.out.print("Key长度不是16位"); return null; } byte[] raw = sKey.getBytes(); SecretKeySpec skeySpec = new ...
关于大附件上传的插件,试了才知道![System.Web.Services.WebMethod] [System.Web.Script.Services.ScriptMethod] public static object GetUploadStatus() { //获取文件长度 ... return null; }
return false; } if(mylog.psw.value.length) { alert("密码不能为少于6位!"); mylog.psw.value==""; mylog.psw.focus(); return false; } if(mylog.retype.value!='AbEF') { alert("您的确认码错误!...
// All of the EXIF properties will return strings to display in the control. // Some of the properties require additional formatting or massaging // of the data once it is returned. Those ...