Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

Java - get the current class name?

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();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...