简体   繁体   English

java:从类中查找项目名称

[英]java: find project name from within class

How can I use java reflection or similar to find project name by just having an instance of the class?如何使用 java 反射或类似方法通过拥有类的实例来查找项目名称? If not the project name -- which is what I really want -- can I find the package name?如果不是项目名称——这是我真正想要的——我能找到包名称吗?

Projects are simply organizational tools used by IDEs, and therefore the project name is not information contained in the class or the JVM.项目只是 IDE 使用的组织工具,因此项目名称不是包含在类或 JVM 中的信息。

To get the package, use Class#getPackage() .要获取包,请使用Class#getPackage() Then, Package#getName() can be called to get the package as the String you see in your code's package declaration.然后,可以调用Package#getName()以获取包作为您在代码的包声明中看到的字符串。

Class<?> clazz = Application.class;
Package package = clazz.getPackage();
System.out.println(package.getName());

Project name is located in your IDE's configure file, eg.项目名称位于 IDE 的配置文件中,例如。 it's .project in Eclipse.它是 Eclipse 中的 .project。 It's a xml file, project name is located in the projectDescription element's child element name.它是一个 xml 文件,项目名称位于 projectDescription 元素的子元素名称中。

Project Name is not known to Java, but is typically the name of the directory where your code is. Java 不知道项目名称,但通常是代码所在目录的名称。

For example, if you are working on a project (in Eclipse or Intellij) and that project is in the folder "~/eclipse-workspace/myproject" then the project name you want is probably "myproject".例如,如果您正在处理一个项目(在 Eclipse 或 Intellij 中)并且该项目位于文件夹“~/eclipse-workspace/myproject”中,那么您想要的项目名称可能是“myproject”。 Be aware that this will not be universal -- or even applicable outside of your development environment.请注意,这不是通用的 —— 甚至不适用于您的开发环境之外。

So what you probably want is the user dir, which in those cases will coincide with the project name.因此,您可能想要的是用户目录,在这些情况下,它与项目名称一致。 If someone just has a binary (jar or class file), it will be where it is executed from -- which may not be the same.如果有人只有一个二进制文件(jar 或类文件),它将是它的执行位置——这可能不一样。

But, if that's what you want, use the following:但是,如果这是您想要的,请使用以下内容:

String userDir = System.getProperty("user.dir");
Path path = Paths.get(userDir);
String project = path.getFileName();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM