如何在 Java 中获得包含包名称的当前类名称?

我正在做一个项目,其中一个要求是如果 main 方法的第二个参数以“ /”开始(对于 linux) ,它应该将其视为一个绝对路径(而不是问题) ,但是如果它不以“ /”开始,它应该获得类的 当前工作路线并将给定的参数附加到它。

我可以通过几种方式得到类名: System.getProperty("java.class.path")new File(".")getCanonicalPath(),等等..。

问题是,这只给了我存储包的目录——也就是说,如果我有一个类存储在“ .../project/this/is/package/name”中,它只会给我“ /project/”并忽略实际 .class files所在的包名。

有什么建议吗?

编辑: 下面是从练习描述中摘录的解释

Sourcedir 可以是绝对的(以“/”开头) ,也可以是相对于我们运行程序的位置的

Source 是 main 方法的一个给定参数。我怎样才能找到那个路径?

166285 次浏览

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.

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.

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

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