如何在Java中获取当前的类名(包括包名)? [英] How to get current class name including package name in Java?
问题描述
我正在一个项目上,一个要求是,如果main方法的第二个参数以"/
"(对于linux)开头,则应将其视为绝对路径(不是问题),但如果不是以"/
"开头,它应该获取该类的当前工作路径,并在其后附加给定的参数.
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.
我可以通过几种方式获取类名:System.getProperty("java.class.path")
,new File(".")
和getCanonicalPath()
,依此类推...
I can get the class name in several ways: System.getProperty("java.class.path")
, new File(".")
and getCanonicalPath()
, and so on...
问题是,这仅给我提供了存储软件包的目录-即,如果我在".../project/this/is/package/name
"中存储了一个类,则只会给我"/project/
",而忽略软件包名称,其中实际的.class files
生活.
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.
有什么建议吗?
这是从练习说明中得到的解释
Here's the explanation, taken from the exercise description
sourcedir可以是绝对的(以"/"开头),也可以是相对于我们运行程序的位置
sourcedir can be either absolute (starting with "/") or relative to where we run the program from
sourcedir是main方法的给定参数.我怎么找到那条路?
sourcedir is a given argument for the main method. how can I find that path?
推荐答案
使用this.getClass().getCanonicalName()
获取完整的类名.
请注意,包/类名("abC")与.class文件(a/b/C.class)的路径不同,通常使用包名/类名来派生路径.坏习惯.类文件/程序包的集合可以位于多个不同的类路径中,这些路径可以是目录或jar文件.
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.
这篇关于如何在Java中获取当前的类名(包括包名)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!