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?

1
  • 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() Commented Jun 20, 2012 at 0:39

3 Answers 3

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());
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.