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

I am working on a project, and one requirement is that if the second argument to the main method starts with " / " (for linux), it should consider it as an absolute path (not a problem), but if it does not start with " / " , it should get the current working path of the class and add the given argument to it.

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

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

Any suggestions?

EDIT: Here is an explanation taken from the exercise description

sourcedir can be either absolute (starting with "/"), or relative to where we start the program

sourcedir is the given argument for the main method. how can i find this way?

+70
java eclipse package classname
Mar 15 2018-12-15T00:
source share
4 answers

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

Note that the package / class name ("abC") is different from the .class file path (a / b / C.class) and that using the package / class name to get the path is usually bad practice. Class files / packages can be in several different class paths, which can be directories or jar files.

+144
Mar 15 2018-12-15T00:
source share

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 represents the MyClass class in the mypackage package, then the above code will print:

Package: mypackage
Class: MyClass
Full identifier: mypackage.MyClass

You can get this information and change it for everything you need, or go check the API for more information.

+24
Mar 15 2018-12-15T00:
source share

A full name is defined as follows:

 String fqn = YourClass.class.getName(); 

But you need to read the classpath resource. Therefore use

 InputStream in = YourClass.getResourceAsStream("resource.txt"); 
+11
Mar 15 2018-12-15T00:
source share

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

+3
Nov 06 '18 at 12:04
source share



All Articles