我所要做的就是获取当前的类名,而java在我的类名的末尾附加了一个无用的无意义的$1。我怎么能摆脱它,只返回实际的类名?

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

当前回答

试试这个 this.getClass(). getcanonicalname()或this.getClass(). getsimplename()。如果是匿名类,则使用this.getClass().getSuperclass().getName()

其他回答

试试这个 this.getClass(). getcanonicalname()或this.getClass(). getsimplename()。如果是匿名类,则使用this.getClass().getSuperclass().getName()

在您的示例中,这可能引用一个匿名类实例。Java通过在外围类的名称后面附加一个$number来为这些类命名。

你可以像这样使用this.getClass().getSimpleName():

import java.lang.reflect.Field;

public class Test {

    int x;
    int y;  

    public String getClassName() {

        String className = this.getClass().getSimpleName(); 
        System.out.println("Name:" + className);
        return className;
    }

    public Field[] getAttributes() {

        Field[] attributes = this.getClass().getDeclaredFields();   
        for(int i = 0; i < attributes.length; i++) {
            System.out.println("Declared Fields" + attributes[i]);    
        }

        return attributes;
    }

    public static void main(String args[]) {

        Test t = new Test();
        t.getClassName();
        t.getAttributes();
    }
}

两个答案的组合。还输出一个方法名:

Class thisClass = new Object(){}.getClass();
String className = thisClass.getEnclosingClass().getSimpleName();
String methodName = thisClass.getEnclosingMethod().getName();
Log.d("app", className + ":" + methodName);

Try,

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

只要你不在静态方法中使用它,它就可以工作。