[Java] 자바 리플렉션, 예제

[Java] 자바 리플렉션, 예제

리플렉션 3줄요약

- 리플렉션은 일종의 API임. 런타임 중에 interface, class들, method들의 행동 과 필드들을 조사하거나 수정할 수 있도록 해줌.

- 리플렉션을 적용할 클래스는 java.lang.reflect pacakge가 제공되어야함.

- 리플렉션을 통해, 런타임에 method를 부를 수 있음, 그것의 접근 지정자와 상관없이.

예제 1. static 필드 접근하기.

import java.lang.reflect.Field; public class test00 { public static void main(String[] args) throws Exception { Employee employee = new Employee(); Object object = employee; Field field = object.getClass().getField("salary"); field.set(object, 11221); System.out.println("Value of salary after " + "applying set is " + employee.salary); } } class Employee { public static short uniqueNo = 239; public static double salary = 121324.13333; public int age = 3; }

출력

Value of salary after applying set is 11221.0

예제 2. 필드 접근하기

import java.lang.reflect.Field; public class test00 { public static void main(String[] args) throws Exception { Employee employee = new Employee(); Object object = employee; Field field = object.getClass().getField("age"); field.set(object, 35); System.out.println("Value of salary after " + "applying set is " + employee.age); } } class Employee { public static short uniqueNo = 239; public static double salary = 121324.13333; public int age = 3; }

출력

Value of salary after applying set is 35

예제 3

import java.lang.reflect.Field; public class test00 { public static void main(String[] args) throws Exception { Employee employee = new Employee(); Object object = employee; Field field = object.getClass().getField("gender"); field.set(object, false); System.out.println("Value of salary after " + "applying set is " + employee.gender); } } class Employee { public static short uniqueNo = 239; public static double salary = 121324.13333; public int age = 3; public boolean gender = true; }

출력

Value of salary after applying set is false

from http://i5i5.tistory.com/590 by ccl(A) rewrite - 2021-11-05 00:01:46