Reputation: 1050
How do I programmatically get the base package of a Java project?
For example I have the following:
my-app
- src
- main
- java
- hello
- world
- util
- exception
- misc
I want to get: hello.world
.
Thank you.
Upvotes: 1
Views: 5329
Reputation: 91
There is a class - Class , that can do this:
Class c = Class.forName("MyClass"); // if you want to specify a class
Class c = this.getClass(); // if you want to use the current class
System.out.println("Package: "+c.getPackage()+"\nClass: "+c.getSimpleName()+"\nFull Identifier: "+c.getName());
c represented the class MyClass in the package mypackage, the above code would print:
Package: mypackage
Class: MyClass
Full Identifier: mypackage.MyClass
You can take this information and modify it in your way.
Upvotes: 2
Reputation: 7828
Suppose we have a class called HelloWorld
and packaged under:
package hello.world.test;
then
HelloWorld.class.getPackage().getName()
will give you hello.world.test
as package name.
In your case, probably you need to remove the last level as:
basePackageName = packageName.substring(0, packageName.lastIndexOf("."));
and have hello.world
.
Upvotes: 1