3

How can I use java reflection or similar to find project name by just having an instance of the class? If not the project name -- which is what I really want -- can I find the package name?

user1467855
  • 3,843
  • 7
  • 28
  • 29
  • 1
    What do you mean by project name? The one you see in your IDE? If you want to know package name provided you have an instance of a class you can do it this way: `instance.getClass().getPackage()` – Igor Nikolaev Jun 20 '12 at 00:39

3 Answers3

8

Projects are simply organizational tools used by IDEs, and therefore the project name is not information contained in the class or the JVM.

To get the package, use Class#getPackage(). Then, Package#getName() can be called to get the package as the String you see in your code's package declaration.

Class<?> clazz = Application.class;
Package package = clazz.getPackage();
System.out.println(package.getName());
FThompson
  • 28,352
  • 13
  • 60
  • 93
0

Project name is located in your IDE's configure file, eg. it's .project in Eclipse. It's a xml file, project name is located in the projectDescription element's child element name.

0

Project Name is not known to Java, but is typically the name of the directory where your code is.

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". 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.

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();
fijiaaron
  • 5,015
  • 3
  • 35
  • 28