處理環境爲您提供了一個Filer
可用於加載(已知)的資源。如果你需要絕對路徑,發現文件或目錄,你可以使用一個JavaFileManager和StandardLocation
:
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null);
Iterable<? extends File> locations = fm.getLocation(StandardLocation.SOURCE_PATH);
如果您使用的是Eclipse,你需要configure it to use the JDK as runtime作爲bennyl在評論中指出。
似乎沒有API,它有義務歸還源位置,所以上述解決方案將無法與某些環境下可靠,只有工作。 Filer例如只需要支持CLASS_OUTPUT
和SOURCE_OUTPUT
。
最簡單的解決方法可能是假定/需要一個特定的項目結構,其中編譯的類位於項目的直接子目錄中(對於大多數IDE bin
或Mavens target
目錄,這是默認設置)。如果你這樣做,那麼你可以使用位於SOURCE_OUTPUT
位置的Filer創建一個臨時資源文件,並從該文件獲取路徑。
Filer filer = processingEnv.getFiler();
FileObject resource = filer.createResource(StandardLocation.CLASS_OUTPUT, "", "tmp", (Element[]) null);
Path projectPath = Paths.get(resource.toUri()).getParent().getParent();
resource.delete();
這並不eclipse下對我的工作 - 從日食執行時ToolProvider.getSystemJavaCompiler()返回NULL(我認爲該eclipse使用自己的編譯器,不尊重這個API) – bennyl
終於找到了一個解決方案 - 空編譯器問題可以通過遵循這個線程的指示來解決:http://stackoverflow.com/questions/9107099/null-javacompiler-in -eclipse - 謝謝你! – bennyl
對我來說這仍然不起作用。 'fm.getLocation(StandardLocation.SOURCE_PATH)'返回null ..我在'AbstractProcessor'的擴展中的init方法中調用了這個函數。任何提示? – jurgenv