繁体   English   中英

Java - 获取当前 class 名称?

[英]Java - get the current class name?

我要做的就是获取当前的 class 名称,并且 java 在我的 class 名称的末尾附加一个无用的废话$1 我怎样才能摆脱它,只返回实际的 class 名称?

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

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

如果您不想要 class 本身,但它声明 class,那么您可以使用getEnclosingClass() 例如:

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

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

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

尝试,

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

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

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

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

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

比方说:

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

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

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

B.this.getClass().getName()

这是一个 Android 变体,但同样的原理也可以用于普通的 Java。

private static final String TAG = YourClass.class.getSimpleName();
private static final String TAG = YourClass.class.getName();

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

我假设匿名 class 正在发生这种情况。 当您创建匿名 class 时,您实际上创建了一个 class,它扩展了您获得的名称的 class。

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

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

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

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

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;
}

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

String className="";

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

System.out.print(className); //Use this to test it works

反射 API

有几个反射 API 返回类,但只有在已经直接或间接获得 Class 时才能访问这些 API。

 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 成员的所有公共类、接口和枚举,包括继承的成员。

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

Character 包含两个成员类 Character.Subset 和
字符.Unicode 块。

 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

有一个封闭的 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.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM