programing

Java - 현재 클래스 이름을 가져옵니다.

goodcopy 2022. 7. 19. 21:40
반응형

Java - 현재 클래스 이름을 가져옵니다.

현재 클래스 이름을 얻으려고 하면 java가 클래스 이름 끝에 쓸모없는 $1을 추가합니다.어떻게 하면 삭제하고 실제 클래스 이름만 반환할 수 있나요?

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

해라,

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

정적 방법으로 사용하지 않는 한 이 방법은 작동합니다.

"$1"은 "쓸데없는 무의미함"이 아닙니다.클래스가 익명인 경우 번호가 추가됩니다.

클래스 자체를 원하지 않고 선언 클래스를 원하는 경우getEnclosingClass(). 예:

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

어떤 정적 유틸리티 방법으로도 이동할 수 있습니다.

그러나 이것은 현재 클래스 이름이 아닙니다.익명 클래스는 해당 클래스와 다른 클래스입니다.내부 계층도 이와 유사합니다.

이것을 사용해 보세요.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 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 A {
    void foo() {
        obj.addHandler(new Handler() {
            void bar() {
                String className=A.this.getClass().getName();
                // ...
            }
        });
    }
}

같은 결과를 얻을 수 있습니다.게다가, 모든 클래스가 컴파일시에 정의되기 때문에, 실제로는 매우 편리합니다.따라서 역동성이 손상되지 않습니다.

그 이상, 클래스가 정말로 중첩되어 있는 경우.A실제로 에 의해 둘러싸여 있다BB의 클래스는 다음과 같이 쉽게 알 수 있습니다.

B.this.getClass().getName()

여기 Android variant가 있습니다만, 플레인 Java에서도 같은 원리를 사용할 수 있습니다.

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

이 예에서는this아마 익명의 클래스인스턴스를 참조하고 있을 겁니다.Java는 이러한 클래스에 이름을 붙입니다.$number에워싸는 클래스의 이름으로 지정합니다.

익명의 수업에서 이런 일이 벌어지고 있는 것 같아요.익명 클래스를 만드는 경우 실제로 이름을 가진 클래스를 확장하는 클래스를 만듭니다.

원하는 이름을 얻을 수 있는 "더 깨끗한" 방법은 다음과 같습니다.

만약 당신의 수업이 익명의 내부 수업이라면,getSuperClass()생성된 클래스를 제공해야 합니다.SOL이 아닌 인터페이스로 작성한 경우, 가능한 한getInterfaces()여러 개의 인터페이스를 사용할 수 있습니다.

"해키한" 방법은 그냥 이름을 알아내는 것이다.getClassName()regex 를 사용하여,$1.

제 경우 다음 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;
}

내 코드로 동작하는 것을 알 수 있었지만, 내 코드로 인해 for 루프 내의 배열에서 클래스가 분리됩니다.

String className="";

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

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

리플렉션

클래스를 반환하는 여러 Reflection API가 있지만 이러한 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()

상속된 멤버를 포함하여 클래스의 멤버인 모든 퍼블릭클래스, 인터페이스 및 enum을 반환합니다.

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

캐릭터에는 2개의 멤버클래스가 포함되어 있습니다.서브셋 및 서브셋
블록유니코드 블록

        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

성격.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.

언급URL : https://stackoverflow.com/questions/6271417/java-get-the-current-class-name

반응형