java compilationtask,如何通过CompilationTask设置编译源

I do not know how to set the source file for a compilationTask.

I tried this:

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

List optionList = new ArrayList(Arrays.asList("-d","build/classes"));

List classes = new ArrayList();

classes.add("src/Hello.java");

CompilationTask task = compiler.getTask(null, null, null, optionList, classes, null);

task.call();

But I get the following error:

Exception in thread "main" java.lang.IllegalArgumentException: Not a valid class name: src/Hello.java

of course, if I put null instead of classes I get "no source files" as no source file was given. I tried using the run function of the JavaCompiler before this but I could not specify the options in the string arguments (Or I do not know how).

Here is the solution:

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

List optionList = new ArrayList(Arrays.asList("-d","build/classes"));

Iterable extends JavaFileObject> classes = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(new File("src/Hello.java")));

CompilationTask task = compiler.getTask(null, null, null, optionList,null, classes);

task.call();

解决方案

Try changing:

classes.add("src/Hello.java");

to:

classes.add(

new SimpleJavaFileObject(new URI("src/Hello.java"), JavaFileObject.Kind.SOURCE)

);

It's a bit verbose but does the job. Of course it could be extracted to a method.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值