Java 如何在没有包的情况下获取类的名称?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2690333/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:52:48  来源:igfitidea点击:

How to get the name of a class without the package?

java

提问by Ola Herrdahl

In C# we have Type.FullNameand Type.Namefor getting the name of a type (class in this case) with or without the namespace (package in java-world).

在 C# 中,我们有Type.FullNameType.Name用于获取带或不带命名空间(java-world 中的包)的类型(在本例中为类)的名称。

What is the java equivalent to Type.Name?

java相当于Type.Name什么?

Clearly there must be a better way than using Class.getName()and strip it of the package name manually.

显然,必须有比Class.getName()手动使用和去除包名更好的方法。

采纳答案by Bozho

Class.getSimpleName()

Class.getSimpleName()

Returns the simple name of the underlying class as given in the source code. Returns an empty string if the underlying class is anonymous.

The simple name of an array is the simple name of the component type with "[]" appended. In particular the simple name of an array whose component type is anonymous is "[]".

返回源代码中给出的基础类的简单名称。如果基础类是匿名的,则返回一个空字符串。

数组的简单名称是附加“[]”的组件类型的简单名称。特别是组件类型为匿名的数组的简单名称是“[]”。

It is actually stripping the package information from the name, but this is hidden from you.

它实际上是从名称中剥离包信息,但这是对您隐藏的。

回答by identy

The following function will work in JDK version 1.5 and above.

以下函数适用于 JDK 1.5 及以上版本。

public String getSimpleName()

回答by Fidel

If using a StackTraceElement, use:

如果使用 StackTraceElement,请使用:

String fullClassName = stackTraceElement.getClassName();
String simpleClassName = fullClassName.substring(fullClassName.lastIndexOf('.') + 1);

System.out.println(simpleClassName);