获取目录路径到.class文件包含主 [英] Getting directory path to .class file containing main

查看:134
本文介绍了获取目录路径到.class文件包含主的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从main中获取包含主要功能的.class文件的路径?

Is it possible to get the path to my .class file containing my main function from within main?

推荐答案

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文件,因此在每种情况下都不起作用(因此 IllegalStateException )。但是,您可以使用此技术找到包含该类的JAR,您可以通过代替 getResourceAsStream()代替 getResource(),无论类是在文件系统还是在JAR中,都可以使用。

Note that most class files are assembled into JAR files so this won't work in every case (hence the IllegalStateException). However, you can locate the JAR that contains the class with this technique, and you can get the content of the class file by substituting a call to getResourceAsStream() in place of getResource(), and that will work whether the class is on the file system or in a JAR.

这篇关于获取目录路径到.class文件包含主的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆