ary*_*axt 258 java class classname
我想要做的就是获取当前的类名,而java 在我的类名末尾添加了一个无用的无意义$ 1.我怎样才能摆脱它并只返回实际的类名?
String className = this.getClass().getName();
Run Code Online (Sandbox Code Playgroud)
Boz*_*zho 235
"1美元"不是"无用的无意义".如果您的班级是匿名的,则会附加一个数字.
如果你不想要类本身,但它的声明类,那么你可以使用getEnclosingClass().例如:
Class<?> enclosingClass = getClass().getEnclosingClass();
if (enclosingClass != null) {
System.out.println(enclosingClass.getName());
} else {
System.out.println(getClass().getName());
}
Run Code Online (Sandbox Code Playgroud)
您可以使用某种静态实用程序方法移动它.
但请注意,这不是当前的类名.匿名类与其封闭类不同.对于内部类,情况类似.
小智 203
尝试,
String className = this.getClass().getSimpleName();
Run Code Online (Sandbox Code Playgroud)
只要您不在静态方法中使用它,这将起作用.
Mir*_*ate 30
尝试使用此
this.getClass().getCanonicalName()或this.getClass().getSimpleName().如果是匿名类,请使用this.getClass().getSuperclass().getName()
您可以这样使用this.getClass().getSimpleName():
import java.lang.reflect.Field;
public class Test {
int x;
int y;
public void getClassName() {
String className = this.getClass().getSimpleName();
System.out.println("Name:" + className);
}
public void getAttributes() {
Field[] attributes = this.getClass().getDeclaredFields();
for(int i = 0; i < attributes.length; i++) {
System.out.println("Declared Fields" + attributes[i]);
}
}
public static void main(String args[]) {
Test t = new Test();
t.getClassName();
t.getAttributes();
}
}
Run Code Online (Sandbox Code Playgroud)