Java 예제가 포함된 Reflection API 튜토리얼
⚡ 스마트 요약
Java 리플렉션 API는 클래스의 필드, 메서드, 생성자를 포함한 클래스의 기능을 런타임에 분석하고 수정합니다. 이 자료에서는 java.lang.reflect 패키지, java.lang.Class의 주요 메서드, 그리고 클래스, 변수, 메서드, 생성자의 메타데이터를 읽는 네 가지 예제를 설명합니다.
반사란 무엇인가? Java?
Java 리플렉션은 런타임에 클래스의 모든 기능을 분석하고 수정하는 프로세스입니다. 리플렉션 API는 다음과 같습니다. Java 런타임에 클래스와 그 멤버(필드, 메서드, 생성자 등)를 조작하는 데 사용됩니다.
리플렉션 API의 한 가지 장점은 다음과 같습니다. Java 클래스의 비공개 멤버도 조작할 수 있다는 점입니다.
java.lang.reflect 패키지는 리플렉션을 구현하기 위한 다양한 클래스를 제공합니다. java.lang.Class 클래스의 메서드는 특정 클래스의 모든 메타데이터를 수집하는 데 사용됩니다.
java.lang.reflect 패키지의 클래스
다음은 목록입니다 여러 Java 수업 리플렉션을 구현하려면 java.lang.reflect 패키지를 사용하십시오.
- 들: 이 클래스는 변수의 데이터 유형, 접근 제어자, 이름 및 값과 같은 선언적 정보를 수집하는 데 사용됩니다.
- 방법 : 이 클래스는 메서드의 접근 제어자, 반환 유형, 이름, 매개변수 유형 및 예외 유형과 같은 선언적 정보를 수집하는 데 사용됩니다.
- 건설자: 이 클래스는 생성자의 접근 제어자, 이름, 매개변수 유형과 같은 선언적 정보를 수집하는 데 사용됩니다.
- 수정 자 : 이 클래스는 특정 접근 제어자에 대한 정보를 수집하는 데 사용됩니다.
java.lang.Class에서 사용되는 메소드
- public String getName(): 클래스의 이름을 반환합니다.
- public 클래스 getSuperclass(): 상위 클래스 참조를 반환합니다.
- public Class[] getInterfaces(): 지정된 클래스가 구현하는 인터페이스 배열을 반환합니다.
- public int getModifiers(): 지정된 클래스의 접근 제한자를 나타내는 정수 값을 반환합니다. 이 값은 주어진 클래스의 접근 지정자를 반환하는 "public static String toString(int i)" 메서드의 매개변수로 전달되어야 합니다.
수업에 대한 완전한 정보를 얻는 방법
에 대한 정보를 얻으려면 변수클래스의 메서드와 생성자를 사용하려면 해당 클래스의 객체를 생성해야 합니다. 다음 예제는 "Class" 클래스의 객체를 생성하는 다양한 방법을 보여줍니다.
public class Guru99ClassObjectCreation { public static void main(String[] args) throws ClassNotFoundException { // 1 - By using Class.forName() method Class c1 = Class.forName("Guru99ClassObjectCreation"); // 2 - By using getClass() method Guru99ClassObjectCreation guru99Obj = new Guru99ClassObjectCreation(); Class c2 = guru99Obj.getClass(); // 3 - By using .class Class c3 = Guru99ClassObjectCreation.class; } }
예시 1: 클래스의 메타데이터를 얻는 방법
다음 예시는 클래스 이름, 상위 클래스 이름, 구현된 인터페이스 및 클래스의 접근 제어자 등의 메타데이터를 가져오는 방법을 보여줍니다.
우리는 아래 클래스의 메타데이터를 가져올 것입니다. Guru99Base.class:
import java.io.Serializable; public abstract class Guru99Base implements Serializable, Cloneable { }
- 수업 이름은 다음과 같습니다: Guru99베이스
- 해당 접근 제어자는 public과 abs입니다.tract
- 인터페이스를 구현했습니다: 직렬화 가능 및 복제 가능
- 명시적으로 어떤 클래스도 상속하지 않았으므로, 해당 클래스의 상위 클래스는 java.lang.Object입니다.
아래 클래스는 메타데이터를 가져옵니다. Guru99Base.class를 출력하세요:
import java.lang.reflect.Modifier; public class Guru99GetclassMetaData { public static void main(String[] args) throws ClassNotFoundException { // Create Class object for Guru99Base.class Class<Guru99Base> guru99ClassObj = Guru99Base.class; // Print name of the class System.out.println("Name of the class is : " + guru99ClassObj.getName()); // Print super class name System.out.println("Name of the super class is : " + guru99ClassObj.getSuperclass().getName()); // Get the list of implemented interfaces using getInterfaces() method Class[] guru99InterfaceList = guru99ClassObj.getInterfaces(); // Print the implemented interfaces using a for-each loop System.out.print("Implemented interfaces are : "); for (Class guru99class1 : guru99InterfaceList) { System.out.print(guru99class1.getName() + " "); } System.out.println(); // Get access modifiers using getModifiers() and Modifier.toString() int guru99AccessModifier = guru99ClassObj.getModifiers(); System.out.println("Access modifiers of the class are : " + Modifier.toString(guru99AccessModifier)); } }
- getName() 메서드를 사용하여 클래스 이름을 출력하세요.
- getSuperclass().getName() 메서드를 사용하여 상위 클래스의 이름을 출력합니다.
- 구현된 인터페이스의 이름을 출력하세요.
- 해당 클래스에서 사용되는 접근 제한자를 출력하세요.
예제 2: 변수의 메타데이터를 얻는 방법
다음 예시는 변수의 메타데이터를 가져오는 방법을 보여줍니다.
여기서 우리는 라는 이름의 클래스를 만들고 있습니다. Guru99VariableMetaData.class에는 몇 가지 변수가 있습니다.
package guru; public class Guru99VariableMetaData { public static int guru99IntVar1 = 1111; static int guru99IntVar2 = 2222; static String guru99StringVar1 = "guru99.com"; static String guru99StringVar2 = "Learning Reflection API"; }
위 클래스의 변수에 대한 메타데이터를 가져오는 단계:
- 위 클래스의 클래스 객체를 생성합니다. 즉, Guru99VariableMetaData.class는 다음과 같습니다.
Guru99VariableMetaData guru99ClassVar = new Guru99VariableMetaData(); Class guru99ClassObjVar = guru99ClassVar.getClass();
- 메타데이터를 필드 배열 형태로 가져오려면 다음을 사용하세요. getFields() or getDeclaredFields() 아래와 같은 방법:
Field[] guru99Field1 = guru99ClassObjVar.getFields(); Field[] guru99Field2 = guru99ClassObjVar.getDeclaredFields();
The getFields() 이 메서드는 지정된 클래스와 해당 상위 클래스의 공개 변수에 대한 메타데이터를 반환합니다.
The getDeclaredFields() 이 메서드는 지정된 클래스에 속한 모든 변수의 메타데이터만 반환합니다.
- "공개 문자열 getName()" 메서드를 사용하여 변수 이름을 가져옵니다.
- "공개 클래스의 getType()" 메서드를 사용하여 변수의 데이터 형식을 가져옵니다.
- "public xxx get(Field)" 메서드를 사용하여 변수 값을 가져옵니다. 여기서 xxx는 바이트, 쇼트 또는 가져오려는 모든 유형의 값이 될 수 있습니다.
- getModifiers() 및 Modifier.toString(int i) 메서드를 사용하여 변수의 접근 제한자를 가져옵니다.
여기서는 클래스에 있는 변수들의 메타데이터를 가져오는 클래스를 작성하고 있습니다. Guru99VariableMetaData.class:
package guru; import java.lang.reflect.Field; import java.lang.reflect.Modifier; public class Guru99VariableMetaDataTest { public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException { // Create Class object for Guru99VariableMetaData.class Guru99VariableMetaData guru99ClassVar = new Guru99VariableMetaData(); Class guru99ClassObjVar = guru99ClassVar.getClass(); // Get the metadata of all the fields of the class Field[] guru99Field1 = guru99ClassObjVar.getDeclaredFields(); // Print name, data types, access modifiers and values of the variables for (Field field : guru99Field1) { System.out.println("Variable name : " + field.getName()); System.out.println("Datatype of the variable : " + field.getType()); int guru99AccessModifiers = field.getModifiers(); System.out.println("Access Modifiers of the variable : " + Modifier.toString(guru99AccessModifiers)); System.out.println("Value of the variable : " + field.get(guru99ClassVar)); System.out.println(); } } }
- 클래스 객체를 생성했습니다. Guru99VariableMetaData.class.
- 변수들의 모든 메타데이터를 필드 배열에 담았습니다.
- 클래스에 있는 모든 변수 이름을 출력하세요. Guru99VariableMetaData.class.
- 클래스에 있는 모든 변수의 데이터 형식을 출력했습니다.
- 클래스에 있는 모든 변수의 접근 제한자를 출력했습니다.
- 클래스에 있는 모든 변수의 값을 출력했습니다.
예제 3: 메서드의 메타데이터를 얻는 방법
다음 예시는 메서드의 메타데이터를 가져오는 방법을 보여줍니다.
여기서 우리는 라는 이름의 클래스를 만들고 있습니다. Guru99MethodMetaData.class에는 몇 가지 메서드가 있습니다.
package guru; import java.sql.SQLException; public class Guru99MethodMetaData { public void guru99Add(int firstElement, int secondElement, String result) throws ClassNotFoundException, ClassCastException { System.out.println("Demo method for Reflection API"); } public String guru99Search(String searchString) throws ArithmeticException, InterruptedException { System.out.println("Demo method for Reflection API"); return null; } public void guru99Delete(String deleteString) throws SQLException { System.out.println("Demo method for Reflection API"); } }
위 클래스의 메서드에 대한 메타데이터를 얻는 단계는 다음과 같습니다.
- 위 클래스의 클래스 객체를 생성합니다. 즉, Guru99MethodMetaData.class는 다음과 같습니다.
Guru99MethodMetaData guru99ClassVar = new Guru99MethodMetaData(); Class guru99ClassObjVar = guru99ClassVar.getClass();
- 아래와 같이 getMethods() 및 getDeclaredMethods() 메서드를 사용하여 메서드 배열에서 메서드 정보를 가져옵니다.
Method[] guru99Method1 = guru99ClassObjVar.getMethods(); Method[] guru99Method2 = guru99ClassObjVar.getDeclaredMethods();
The get메소드() 이 메서드는 지정된 클래스와 해당 상위 클래스의 공개 메서드에 대한 메타데이터를 반환합니다. getDeclaredMethods() 이 메서드는 지정된 클래스의 모든 메서드에 대한 메타데이터만 반환합니다.
- 메서드 이름을 가져오려면 다음을 사용하세요. getName () 방법.
- 메서드의 반환 타입을 가져오려면 다음을 사용하세요. getReturnType() 방법.
- 메서드의 접근 제한자를 가져오려면 다음을 사용하세요. getModifier() 수정자.toString(int i) 방법.
- 메서드 매개변수 유형을 가져오려면 다음을 사용하세요. getParameterTypes() 클래스 배열을 반환하는 메서드입니다.
- 예외를 발생시키려면 다음을 사용하세요. getExceptionTypes() 클래스 배열을 반환하는 메서드입니다.
여기서는 클래스에 있는 메서드의 메타데이터를 얻기 위한 클래스를 작성하고 있습니다. Guru99MethodMetaData.class:
package guru; import java.lang.reflect.Method; import java.lang.reflect.Modifier; public class Guru99MethodMetaDataTest { public static void main(String[] args) { // Create Class object for Guru99MethodMetaData.class Class guru99ClassObj = Guru99MethodMetaData.class; // Get the metadata of all the methods using getDeclaredMethods() Method[] guru99Methods = guru99ClassObj.getDeclaredMethods(); for (Method method : guru99Methods) { System.out.println("Name of the method : " + method.getName()); System.out.println("Return type of the method : " + method.getReturnType()); int guru99ModifierList = method.getModifiers(); System.out.println("Method access modifiers : " + Modifier.toString(guru99ModifierList)); Class[] guru99ParamList = method.getParameterTypes(); System.out.print("Method parameter types : "); for (Class class1 : guru99ParamList) { System.out.print(class1.getName() + " "); } System.out.println(); Class[] guru99ExceptionList = method.getExceptionTypes(); System.out.print("Exception thrown by method : "); for (Class class1 : guru99ExceptionList) { System.out.print(class1.getName() + " "); } System.out.println(); } } }
- 클래스 객체를 생성했습니다. Guru99MethodMetaData.class.
- 모든 메서드의 메타데이터를 Method 배열에 저장했습니다.
- 클래스에 있는 모든 메서드 이름을 출력했습니다.
- 클래스 내 메서드들의 반환 타입을 출력했습니다.
- 클래스 내 모든 메서드의 접근 제한자를 출력했습니다.
- 메서드의 매개변수 유형을 출력했습니다.
- 메서드에서 발생한 예외를 출력했습니다.
예제 4: 생성자의 메타데이터를 얻는 방법
다음 예시는 생성자의 메타데이터를 가져오는 방법을 보여줍니다.
여기서 우리는 라는 이름의 클래스를 만들고 있습니다. Guru99Constructor.class에는 다양한 생성자가 있습니다.
package guru; import java.rmi.RemoteException; import java.sql.SQLException; public class Guru99Constructor { public Guru99Constructor(int no) throws ClassCastException, ArithmeticException { } public Guru99Constructor(int no, String name) throws RemoteException, SQLException { } public Guru99Constructor(int no, String name, String address) throws InterruptedException { } }
여기서는 클래스에 있는 생성자들의 메타데이터를 가져오는 클래스를 작성하고 있습니다. Guru99 생성자 클래스:
package guru; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; public class Guru99ConstructorMetaDataTest { public static void main(String[] args) { // Create Class object for Guru99Constructor.class Class guru99Class = Guru99Constructor.class; // Get all the constructor information in the Constructor array Constructor[] guru99ConstructorList = guru99Class.getConstructors(); for (Constructor constructor : guru99ConstructorList) { System.out.println("Constructor name : " + constructor.getName()); int guru99Modifiers = constructor.getModifiers(); System.out.println("Constructor modifier : " + Modifier.toString(guru99Modifiers)); Class[] guru99ParamList = constructor.getParameterTypes(); System.out.print("Constructor parameter types : "); for (Class class1 : guru99ParamList) { System.out.print(class1.getName() + " "); } System.out.println(); Class[] guru99ExceptionList = constructor.getExceptionTypes(); System.out.print("Exception thrown by constructors : "); for (Class class1 : guru99ExceptionList) { System.out.print(class1.getName() + " "); } System.out.println(); } } }
- 클래스 객체를 생성했습니다. Guru99 생성자.클래스.
- 모든 생성자의 메타데이터를 Constructor 배열에 저장했습니다.
- 클래스에 있는 모든 생성자 이름을 출력했습니다.
- 클래스의 생성자에 대한 모든 접근 제한자를 출력했습니다.
- 생성자의 매개변수 유형을 출력했습니다.
- 생성자에서 발생한 예외들을 출력했습니다.

















