获取包含 main .class 文件的目录路径

2022-09-04 07:17:53

是否可以从 main 中获取包含我的 main 函数的 .class 文件的路径?


答案 1
URL main = Main.class.getResource("Main.class");
if (!"file".equalsIgnoreCase(main.getProtocol()))
  throw new IllegalStateException("Main class is not stored in a file.");
File path = new File(main.getPath());

请注意,大多数类文件都组装成 JAR 文件,因此这并非在所有情况下都有效(因此 )。但是,您可以使用此技术找到包含该类的 JAR,并且可以通过替换 的调用来获取类文件的内容,无论该类是在文件系统上还是在 JAR 中,这都将起作用。IllegalStateExceptiongetResourceAsStream()getResource()