eri*_*son 28
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());
Run Code Online (Sandbox Code Playgroud)
请注意,大多数类文件都组装成JAR文件,因此在每种情况下都不起作用(因此IllegalStateException).但是,您可以使用此技术找到包含该类的JAR,并且您可以通过替换调用代替来获取类文件的内容,无论该类是在文件系统上还是在JAR getResourceAsStream()中getResource(),这都将起作用.