如何在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 文件
所在的包名.
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()
获取完整的类名.
Use this.getClass().getCanonicalName()
to get the full class name.
请注意,包/类名 ("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.
相关文章