如何在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中获取当前类名,包括包名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

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

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)