IT

Java-현재 클래스 이름을 얻습니까?

lottoking 2020. 4. 1. 08:12
반응형

Java-현재 클래스 이름을 얻습니까?


내가하려고하는 것은 현재 클래스 이름을 얻는 것 뿐이며 java는 클래스 이름 끝에 쓸모없는 넌센스 $ 1추가합니다 . 어떻게 제거하고 실제 클래스 이름 만 반환 할 수 있습니까?

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

"$ 1"은 "무의미한 의미가 없습니다". 수업이 익명 인 경우 숫자가 추가됩니다.

클래스 자체는 원하지 않지만 클래스를 선언하려면을 사용할 수 있습니다 getEnclosingClass(). 예를 들면 다음과 같습니다.

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

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

그러나 이것은 현재 클래스 이름이 아닙니다. 익명 클래스는 둘러싼 클래스와 다른 클래스입니다. 내부 클래스의 경우도 마찬가지입니다.


시험,

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

정적 메소드에서 사용하지 않는 한 작동합니다.


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

이 답변은 늦었지만 익명 처리기 클래스의 컨텍스트 에서이 작업을 수행하는 다른 방법이 있다고 생각합니다.

의 말을하자:

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

동일한 결과를 얻을 수 있습니다. 또한 모든 클래스가 컴파일 타임에 정의되므로 동적이 손상되지 않으므로 실제로 매우 편리합니다.

그보다 클래스가 실제로 중첩되어있는 경우, 즉 A실제로로 묶인 경우 BB 클래스는 쉽게 다음과 같이 알 수 있습니다.

B.this.getClass().getName()


두 답변의 조합. 또한 메소드 이름을 인쇄합니다.

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

귀하의 예에서 this아마도 익명 클래스 인스턴스를 가리킬 것입니다. Java는 엔 $number클로징 클래스의 이름에 a 추가하여 해당 클래스에 이름을 제공합니다 .


나는 이것이 익명의 클래스에서 일어나고 있다고 가정합니다. 익명 클래스를 만들면 실제로 이름을 가진 클래스를 확장하는 클래스를 만듭니다.

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

클래스가 익명의 내부 클래스 인 getSuperClass()경우 클래스가 작성된 클래스를 제공해야합니다. 당신이 할 수있는 최선의 방법은 getInterfaces()하나 이상의 인터페이스를 제공 할 수 있기 때문에 일종의 SOL보다 인터페이스에서 생성 한 것입니다 .

"hacky"방법은 이름을 가져 와서 getClassName()정규식을 사용하여를 삭제하는 것 $1입니다.


내 코드에서 작동하는 것으로 나타 났지만 내 코드는 for 루프 내의 배열에서 클래스를 가져옵니다.

String className="";

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

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

리플렉션 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()

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

        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

캐릭터. 캐릭터 캐시.

        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

반응형