How to get current class name including package name in Java?

JavaEclipsePackageClassname

Java Problem Overview


I'm working on a project and one requirement is if the 2nd argument for the main method starts with “/” (for linux) it should consider it as an absolute path (not a problem), but if it doesn't start with “/”, it should get the current working path of the class and append to it the given argument.

I can get the class name in several ways: System.getProperty("java.class.path"), new File(".") and getCanonicalPath(), and so on...

The problem is, this only gives me the directory in which the packages are stored - i.e. if I have a class stored in ".../project/this/is/package/name", it would only give me "/project/" and ignores the package name where the actual .class files lives.

Any suggestions?

EDIT: Here's the explanation, taken from the exercise description

> sourcedir can be either absolute (starting with “/”) or relative to where we run the program from

sourcedir is a given argument for the main method. how can I find that path?

Java Solutions


Solution 1 - Java

Use this.getClass().getCanonicalName() to get the full class name.

Note that a package / class name ("a.b.C") is different from the path of the .class files (a/b/C.class), and that using the package name / class name to derive a path is typically bad practice. Sets of class files / packages can be in multiple different class paths, which can be directories or jar files.

Solution 2 - Java

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

If 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 for whatever you need, or go check the API for more information.

Solution 3 - Java

The fully-qualified name is opbtained as follows:

String fqn = YourClass.class.getName();

But you need to read a classpath resource. So use

InputStream in = YourClass.getResourceAsStream("resource.txt");

Solution 4 - Java

use this.getClass().getName() to get packageName.className and use this.getClass().getSimpleName() to get only class name

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLa bla blaView Question on Stackoverflow
Solution 1 - JavaThe NailView Answer on Stackoverflow
Solution 2 - JavaJon EgelandView Answer on Stackoverflow
Solution 3 - JavaBozhoView Answer on Stackoverflow
Solution 4 - JavaMd. Zahangir AlamView Answer on Stackoverflow