如何在Java中获取当前类名,包括包名?

How to get current class name including package name in Java?(如何在Java中获取当前类名,包括包名?)
本文介绍了如何在Java中获取当前类名,包括包名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在做一个项目,一个要求是如果 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.

这篇关于如何在Java中获取当前类名,包括包名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Sending a keyboard event from java to any application (on-screen-keyboard)(将键盘事件从 java 发送到任何应用程序(屏幕键盘))
How to make JComboBox selected item not changed when scrolling through its popuplist using keyboard(使用键盘滚动其弹出列表时如何使 JComboBox 所选项目不更改)
Capturing keystrokes without focus(在没有焦点的情况下捕获击键)
How can I position a layout right above the android on-screen keyboard?(如何将布局放置在 android 屏幕键盘的正上方?)
How to check for key being held down on startup in Java(如何检查在Java中启动时按住的键)
Android - Get keyboard key press(Android - 获取键盘按键)