본문으로 바로가기

자바(Java)에서는 Object 클래스에 있는 getClass()를 통해 여러가지 클래스에 대한 메타 속성 정보를 얻을 수 있습니다.이 처럼 객체를 통해 클래스의 정보를 분석하는 것을 리플렉션(reflection - java.lang.reflect)이라 하고 주로 클래스를 동적으로 로딩하거나 디컴파일 할 때 많이 활용됩니다.

자주 사용되는 메서드로는 getName()은 각 패키지명이 포함된 클래스명 getSimpleName()패키지 경로가 포함되지 않은 클래스명만 추출해내고 getMethods(),getFields()은 각각 클래스의 메서드와 필드 목록을 뽑아냅니다. 간단한 예제를 통해 클래스의 이름과 패키지명 메서드, 필드 목록을 출력해보도록 하겠습니다. 
public class TestClass {

    public String field1;
    public String field2;

    public void method1() {}
    public void method2() {}
}
public static void main(){

    TestClass testClass = new TestClass();

    System.out.println("getName()      : " + testClass.getClass().getName());
    System.out.println("getSimpleName()  : " + testClass.getClass().getSimpleName());
    System.out.println("===========getMethods()===========");
    for(Method method : testClass.getClass().getMethods()){
        System.out.println("method          : " + method.getName());
    }
    System.out.println("===========getFields()===========");
    for(Field field : testClass.getClass().getFields()){
        System.out.println("field           : " + field.getName());
    }
}
▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼

getSimpleName()        : TestClass
getName()              : com.ifuwanna.cls.TestClass
===========getMethods()===========
method                 : method1
method                 : method2
method                 : wait
method                 : wait
method                 : wait
method                 : equals
method                 : toString
method                 : hashCode
method                 : getClass
method                 : notify
method                 : notifyAll
===========getFields()===========
field                  : field1
field                  : field2


getClass로 가져온 Object는 Class<?>와 동일하게 위 메서드 이외에도 아래와 같은 여러가지 기능을 제공하니 참고해주세요  

Modifier and TypeMethod and Description
<U> Class<? extends U>asSubclass(Class<U> clazz)
Casts this Class object to represent a subclass of the class represented by the specified class object.
Tcast(Object obj)
Casts an object to the class or interface represented by this Class object.
booleandesiredAssertionStatus()
Returns the assertion status that would be assigned to this class if it were to be initialized at the time this method is invoked.
static Class<?>forName(String className)
Returns the Class object associated with the class or interface with the given string name.
static Class<?>forName(String name, boolean initialize, ClassLoader loader)
Returns the Class object associated with the class or interface with the given string name, using the given class loader.
<A extends Annotation
A
getAnnotation(Class<A> annotationClass)
Returns this element's annotation for the specified type if such an annotation is present, else null.
Annotation[]getAnnotations()
Returns all annotations present on this element.
StringgetCanonicalName()
Returns the canonical name of the underlying class as defined by the Java Language Specification.
Class<?>[]getClasses()
Returns an array containing Class objects representing all the public classes and interfaces that are members of the class represented by this Class object.
ClassLoadergetClassLoader()
Returns the class loader for the class.
Class<?>getComponentType()
Returns the Class representing the component type of an array.
Constructor<T>getConstructor(Class<?>... parameterTypes)
Returns a Constructor object that reflects the specified public constructor of the class represented by this Class object.
Constructor<?>[]getConstructors()
Returns an array containing Constructor objects reflecting all the public constructors of the class represented by this Class object.
Annotation[]getDeclaredAnnotations()
Returns all annotations that are directly present on this element.
Class<?>[]getDeclaredClasses()
Returns an array of Class objects reflecting all the classes and interfaces declared as members of the class represented by this Class object.
Constructor<T>getDeclaredConstructor(Class<?>... parameterTypes)
Returns a Constructor object that reflects the specified constructor of the class or interface represented by this Class object.
Constructor<?>[]getDeclaredConstructors()
Returns an array of Constructor objects reflecting all the constructors declared by the class represented by this Class object.
FieldgetDeclaredField(String name)
Returns a Field object that reflects the specified declared field of the class or interface represented by this Class object.
Field[]getDeclaredFields()
Returns an array of Field objects reflecting all the fields declared by the class or interface represented by this Class object.
MethodgetDeclaredMethod(String name, Class<?>... parameterTypes)
Returns a Method object that reflects the specified declared method of the class or interface represented by this Class object.
Method[]getDeclaredMethods()
Returns an array of Method objects reflecting all the methods declared by the class or interface represented by this Class object.
Class<?>getDeclaringClass()
If the class or interface represented by this Class object is a member of another class, returns the Class object representing the class in which it was declared.
Class<?>getEnclosingClass()
Returns the immediately enclosing class of the underlying class.
Constructor<?>getEnclosingConstructor()
If this Class object represents a local or anonymous class within a constructor, returns a Constructor object representing the immediately enclosing constructor of the underlying class.
MethodgetEnclosingMethod()
If this Class object represents a local or anonymous class within a method, returns a Method object representing the immediately enclosing method of the underlying class.
T[]getEnumConstants()
Returns the elements of this enum class or null if this Class object does not represent an enum type.
FieldgetField(String name)
Returns a Field object that reflects the specified public member field of the class or interface represented by this Class object.
Field[]getFields()
Returns an array containing Field objects reflecting all the accessible public fields of the class or interface represented by this Class object.
Type[]getGenericInterfaces()
Returns the Types representing the interfaces directly implemented by the class or interface represented by this object.
TypegetGenericSuperclass()
Returns the Type representing the direct superclass of the entity (class, interface, primitive type or void) represented by this Class.
Class<?>[]getInterfaces()
Determines the interfaces implemented by the class or interface represented by this object.
MethodgetMethod(String name, Class<?>... parameterTypes)
Returns a Method object that reflects the specified public member method of the class or interface represented by this Class object.
Method[]getMethods()
Returns an array containing Method objects reflecting all the public member methods of the class or interface represented by this Class object, including those declared by the class or interface and those inherited from superclasses and superinterfaces.
intgetModifiers()
Returns the Java language modifiers for this class or interface, encoded in an integer.
StringgetName()
Returns the name of the entity (class, interface, array class, primitive type, or void) represented by this Class object, as a String.
PackagegetPackage()
Gets the package for this class.
ProtectionDomaingetProtectionDomain()
Returns the ProtectionDomain of this class.
URLgetResource(String name)
Finds a resource with a given name.
InputStreamgetResourceAsStream(String name)
Finds a resource with a given name.
Object[]getSigners()
Gets the signers of this class.
StringgetSimpleName()
Returns the simple name of the underlying class as given in the source code.
Class<? super T>getSuperclass()
Returns the Class representing the superclass of the entity (class, interface, primitive type or void) represented by this Class.
TypeVariable<Class<T>>[]getTypeParameters()
Returns an array of TypeVariable objects that represent the type variables declared by the generic declaration represented by this GenericDeclaration object, in declaration order.
booleanisAnnotation()
Returns true if this Class object represents an annotation type.
booleanisAnnotationPresent(Class<? extends Annotation> annotationClass)
Returns true if an annotation for the specified type is present on this element, else false.
booleanisAnonymousClass()
Returns true if and only if the underlying class is an anonymous class.
booleanisArray()
Determines if this Class object represents an array class.
booleanisAssignableFrom(Class<?> cls)
Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter.
booleanisEnum()
Returns true if and only if this class was declared as an enum in the source code.
booleanisInstance(Object obj)
Determines if the specified Object is assignment-compatible with the object represented by this Class.
booleanisInterface()
Determines if the specified Class object represents an interface type.
booleanisLocalClass()
Returns true if and only if the underlying class is a local class.
booleanisMemberClass()
Returns true if and only if the underlying class is a member class.
booleanisPrimitive()
Determines if the specified Class object represents a primitive type.
booleanisSynthetic()
Returns true if this class is a synthetic class; returns false otherwise.
TnewInstance()
Creates a new instance of the class represented by this Class object.
StringtoString()
Converts the object to a string.