虽然您没有明确提到它,但我认为您正在运行带有 modules(JDK 9+)的 Java 版本,但您一直遵循的指南适用于从 Java 6 开始的早期版本。这就是为什么您收到有关不受支持的 listLocationsForModules 的错误,因为 JDK 开发人员使用抛出 UnsupportedOperationException 的默认方法对 FileManager 进行了改造。
如果你真的不想使用大于 8 的 Java 版本,我会坚持使用 JDK8,它会容易得多!
我会继续假设您确实想使用 Java 9 及更高版本(在 Java 11 中测试了我的代码):
对于处理模块,您的文件管理器委托给标准文件管理器就足够了:
@Override
public Location getLocationForModule(Location location, String moduleName) throws IOException {
return standardFileManager.getLocationForModule(location, moduleName);
}
@Override
public Location getLocationForModule(Location location, JavaFileObject fo) throws IOException {
return standardFileManager.getLocationForModule(location, fo);
}
@Override
public Iterable<Set<Location>> listLocationsForModules(Location location) throws IOException {
return standardFileManager.listLocationsForModules(location);
}
@Override
public String inferModuleName(Location location) throws IOException {
return standardFileManager.inferModuleName(location);
}
我还发现有必要修改 Atamur 的代码以显式检查基本 java 模块(以便我们可以在 Java 9+ 中解析 java.lang!)并像对平台类一样委托给标准文件管理器以前版本中的路径:
@Override
public Iterable<JavaFileObject> list(Location location, String packageName, Set<JavaFileObject.Kind> kinds, boolean recurse) throws IOException {
boolean baseModule = location.getName().equals("SYSTEM_MODULES[java.base]");
if (baseModule || location == StandardLocation.PLATFORM_CLASS_PATH) { // **MODIFICATION CHECK FOR BASE MODULE**
return standardFileManager.list(location, packageName, kinds, recurse);
} else if (location == StandardLocation.CLASS_PATH && kinds.contains(JavaFileObject.Kind.CLASS)) {
if (packageName.startsWith("java") || packageName.startsWith("com.sun")) {
return standardFileManager.list(location, packageName, kinds, recurse);
} else { // app specific classes are here
return finder.find(packageName);
}
}
return Collections.emptyList();
}
更新
其他几点:
提取嵌入式 Spring Boot 类:
通过查找 '!' 的最后一个索引来获取 jarUri在每个 packageFolderURL 中,就像在 Taeyun Kim's comment 中一样,而不是在原始示例中的第一个。
private List<JavaFileObject> processJar(URL packageFolderURL) {
List<JavaFileObject> result = new ArrayList<JavaFileObject>();
try {
// Replace:
// String jarUri = packageFolderURL.toExternalForm().split("!")[0];
// With:
String externalForm = packageFolderURL.toExternalForm();
String jarUri = externalForm.substring(0, externalForm.lastIndexOf('!'));
JarURLConnection jarConn = (JarURLConnection) packageFolderURL.openConnection();
String rootEntryName = jarConn.getEntryName();
int rootEnd = rootEntryName.length()+1;
// ...
这允许包PackageInternalsFinder 将带有完整URI 的CustomJavaFileObject 返回到嵌入式spring jar(在BOOT-INF/lib 下)中的类,然后使用spring boot jar URI handler 解析,其注册方式与in this answer 解释类似。 URI 处理应该通过 spring boot 自动发生。