动态代理遇到:All compilation units must be of SOURCE kind

		JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
				
		StandardJavaFileManager fileMgr = comp.getStandardFileManager(null, null, null);
		Iterable it = fileMgr.getJavaFileObjects(fileName);
		
		CompilationTask t  =  comp.getTask(null, fileMgr, null, options, null, it);

上面这样写的话,会报错: All compilation units must be of SOURCE kind


解决办法如下,需要加一个类: JavaSourceFromString。生成compilation units: it的时候不用文件路径fileName, 而是用代码的String: src.

		JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
		
		StandardJavaFileManager fileMgr = comp.getStandardFileManager(null, null, null);
		JavaSourceFromString srcObj =  new JavaSourceFromString("Proxy1", src);
		Iterable it =  Arrays.asList(srcObj);
		
		CompilationTask t  =  comp.getTask(null, fileMgr, null, options, null, it);





class JavaSourceFromString extends SimpleJavaFileObject {
	String code;
    JavaSourceFromString(String name, String code) {
		super(URI.create("string:///" + name.replace('.', '/') + Kind.SOURCE.extension), Kind.SOURCE);
		System.out.println(URI.create("string:///" + name.replace('.', '/') + Kind.SOURCE.extension));
		System.out.println(Kind.SOURCE);
		// TODO Auto-generated constructor stub
		this.code = code;
	}
    
    public CharSequence getCharContent(boolean ignoreEncodeingErrors) {
    	return code;
    }
    


你可能感兴趣的:(Java)