Java - 获取当前的类名?

问题描述 投票:244回答:10

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

String className = this.getClass().getName();
java class classname
10个回答
226
投票

“1美元”不是“无用的无意义”。如果您的班级是匿名的,则会附加一个数字。

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

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

您可以使用某种静态实用程序方法移动它。

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


-3
投票

Reflection APIs

有几个Reflection API可以返回类,但只有在已经直接或间接获得Class的情况下才能访问这些类。

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()

返回作为类成员的所有公共类,接口和枚举,包括继承的成员。

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

Character包含两个成员类Character.Subset和 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

有一个封闭的课程。

        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.

194
投票

尝试,

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

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


27
投票

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


9
投票

您可以使用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();
    }
}

3
投票

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

让我们说:

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

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

如上所述,如果该类实际上是嵌套的,即A实际上被B包围,则B类很容易被称为:

B.this.getClass().getName()

3
投票

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

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

2
投票

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


1
投票

我假设这是一个匿名课程。当您创建一个匿名类时,您实际上创建了一个类,该类扩展了您的名称所在的类。

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

如果你的类是一个匿名的内部类,getSuperClass()应该给你创建它的类。如果你从一个接口创建它而不是你的SOL,因为你可以做的最好的是getInterfaces(),它可能会给你多个接口。

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


-3
投票

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

String className="";

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

System.out.print(className); //Use this to test it works
© www.soinside.com 2019 - 2024. All rights reserved.