获取当前类名,包括包 [英] Getting current class name including package
问题描述
我可以通过几种方式获取类名: System.getProperty(java.class.path)
, new File(。)
和 getCanonicalPath()
,等等..
问题是,这只给我包裹存储的目录 - 即如果我有一个类存储在... / project / this / is / package / name中,它只会给我/ project /,并忽略实际的.class文件的包名。 p>
任何建议?
编辑:
这是从练习描述中获得的解释
sourcedir可以是绝对的(以/开头)或相对性e我们从
sourcedir是一个给定的参数,主要方法运行程序。如何找到该路径?
使用 this.getClass()。getCanonicalName() code>获取完整的类名。
请注意,一个包/类名称(abC)与.class文件的路径不同( a / b / C.class),并且使用包名/类名来导出路径通常是不好的做法。类文件/包的集合可以在多个不同的类路径中,可以是目录或jar文件。
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 are.
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?
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.
这篇关于获取当前类名,包括包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!