Java - 获取当前类名? [英] Java - get the current class name?

查看:128
本文介绍了Java - 获取当前类名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所有我想要做的是获取当前的类名,和java附加一个无用的无意义 $ 1 到我的类名的末尾。如何摆脱它,只返回实际的类名?

All I am trying to do is to get the current class name, and java appends a useless non-sense $1 to the end of my class name. How can I get rid of it and only return the actual class name?

String className = this.getClass().getName();


推荐答案

$ 1不是无用的无意义。如果你的类是匿名的,则附加一个数字。

The "$1" is not "useless non-sense". If your class is anonymous, a number is appended.

如果你不想要类本身,而是它的声明类,那么你可以使用 getEnclosingClass()。例如:

If you don't want the class itself, but its declaring class, then you can use getEnclosingClass(). For example:

Class<?> enclosingClass = getClass().getEnclosingClass();
if (enclosingClass != null) {
  System.out.println(enclosingClass.getName());
} else {
  System.out.println(getClass().getName());
}

您可以在一些静态实用程序方法中移动它。

You can move that in some static utility method.

但是请注意,这不是当前的类名。匿名类是与其封闭类不同的类。内部类的情况类似。

But note that this is not the current class name. The anonymous class is different class than its enclosing class. The case is similar for inner classes.

这篇关于Java - 获取当前类名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆