329

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

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

12 回答 12

289

尝试,

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

只要您不在静态方法中使用它,这将起作用。

于 2012-06-12T20:41:34.270 回答
280

“$1”不是“无用的废话”。如果您的班级是匿名的,则会附加一个数字。

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

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

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

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

于 2011-06-07T20:49:27.270 回答
34

尝试使用此 this.getClass().getCanonicalName()this.getClass().getSimpleName(). 如果是匿名类,请使用this.getClass().getSuperclass().getName()

于 2011-06-07T20:53:46.330 回答
13

你可以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();
    }
}
于 2015-09-25T22:22:14.867 回答
4

两个答案的组合。还打印一个方法名称:

Class thisClass = new Object(){}.getClass();
String className = thisClass.getEnclosingClass().getSimpleName();
String methodName = thisClass.getEnclosingMethod().getName();
Log.d("app", className + ":" + methodName);
于 2017-03-29T22:14:18.240 回答
3

这个答案很晚,但我认为在匿名处理程序类的上下文中还有另一种方法可以做到这一点。

比方说:

class A {
    void foo() {
        obj.addHandler(new Handler() {
            void bar() {
                String className=A.this.getClass().getName();
                // ...
            }
        });
    }
}

它将达到相同的结果。此外,它实际上非常方便,因为每个类都是在编译时定义的,因此不会损坏动态性。

在此之上,如果该类是真正嵌套的,即A实际上被 包围B,则 B 的类可以很容易地称为:

B.this.getClass().getName()
于 2015-02-23T21:40:11.417 回答
2

在您的示例中,this可能指的是匿名类实例。Java 通过将 a 附加$number到封闭类的名称来为这些类命名。

于 2011-06-07T20:51:31.907 回答
2

这是一个 Android 变体,但同样的原理也可以在纯 Java 中使用。

private static final String TAG = YourClass.class.getSimpleName();
private static final String TAG = YourClass.class.getName();
于 2020-04-30T06:16:43.907 回答
1

我假设这发生在一个匿名类上。当您创建一个匿名类时,您实际上创建了一个扩展您所获得名称的类的类。

获得所需名称的“更清洁”方法是:

如果您的类是匿名内部类,getSuperClass()则应为您提供创建它的类。如果你从一个界面创建它,那么你就是一种 SOL,因为你能做的最好的事情就是getInterfaces()它可能会给你多个界面。

“hacky”方法是获取名称getClassName()并使用正则表达式删除$1.

于 2011-06-07T21:06:24.883 回答
0

就我而言,我使用这个 Java 类:

private String getCurrentProcessName() {
    String processName = "";
    int pid = android.os.Process.myPid();
    
    ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    for (ActivityManager.RunningAppProcessInfo processInfo : manager.getRunningAppProcesses()) {
        if (processInfo.pid == pid) {
            processName = processInfo.processName;
            break;
        }
    }
    
    return processName;
}
于 2021-01-06T06:57:47.140 回答
-2

我发现这适用于我的代码,但是我的代码正在将类从 for 循环中的数组中取出。

String className="";

className = list[i].getClass().getCanonicalName();

System.out.print(className); //Use this to test it works
于 2014-05-01T02:04:33.300 回答
-4

Reflection APIs

There are several Reflection APIs which return classes but these may only be accessed if a Class has already been obtained either directly or indirectly.

Class.getSuperclass()
     Returns the super class for the given class.

        Class c = javax.swing.JButton.class.getSuperclass();
        The super class of javax.swing.JButton is javax.swing.AbstractButton.

        Class.getClasses()

Returns all the public classes, interfaces, and enums that are members of the class including inherited members.

        Class<?>[] c = Character.class.getClasses();

Character contains two member classes Character.Subset and
Character.UnicodeBlock.

        Class.getDeclaredClasses()
         Returns all of the classes interfaces, and enums that are explicitly declared in this class.

        Class<?>[] c = Character.class.getDeclaredClasses();
     Character contains two public member classes Character.Subset and Character.UnicodeBlock and one private class

Character.CharacterCache.

        Class.getDeclaringClass()
        java.lang.reflect.Field.getDeclaringClass()
        java.lang.reflect.Method.getDeclaringClass()
        java.lang.reflect.Constructor.getDeclaringClass()
     Returns the Class in which these members were declared. Anonymous Class Declarations will not have a declaring class but will

have an enclosing class.

        import java.lang.reflect.Field;

            Field f = System.class.getField("out");
            Class c = f.getDeclaringClass();
            The field out is declared in System.
            public class MyClass {
                static Object o = new Object() {
                    public void m() {} 
                };
                static Class<c> = o.getClass().getEnclosingClass();
            }

     The declaring class of the anonymous class defined by o is null.

    Class.getEnclosingClass()
     Returns the immediately enclosing class of the class.

    Class c = Thread.State.class().getEnclosingClass();
     The enclosing class of the enum Thread.State is Thread.

    public class MyClass {
        static Object o = new Object() { 
            public void m() {} 
        };
        static Class<c> = o.getClass().getEnclosingClass();
    }
     The anonymous class defined by o is enclosed by MyClass.
于 2016-09-08T06:29:27.033 回答