본문 바로가기

자바

reflection

리플렉션은 객체를 통해 클래스의 정보를 분석해내는 프로그램 기법이다.

클래스 파일의 위치나 이름만 있으면 해당 클래스의 정보를 얻어내고, 객체를 생성하는 것 또한 가능하게 해주는 유연한 프로그래밍을 위한 기법이다. 동적으로 객체를 생성하는 것 또한 가능해진다.

 

Class 클래스

Class 클래스는 리플렉션의 기초가 되는 클래스이다.

Class 클래스에는 자바에서 사용되는 클래스들에 대한 구조를 가지고 있는 Class이다.

 

예제

package reflection;

public class UserDto {

	private String id;
	private String pwd;
	private String name;
	private Integer birthDate;
	
	public UserDto() {
	}

	public UserDto(String id, String pwd, String name, Integer birthDate) {
		super();
		this.id = id;
		this.pwd = pwd;
		this.name = name;
		this.birthDate = birthDate;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getPwd() {
		return pwd;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getBirthDate() {
		return birthDate;
	}

	public void setBirthDate(Integer birthDate) {
		this.birthDate = birthDate;
	}

	@Override
	public String toString() {
		return "UserDto [id=" + id + ", pwd=" + pwd + ", name=" + name + ", birthDate=" + birthDate + "]";
	}
}

fㅁㅇㄴㄹ

ㅁㅇㄹ

ㅁㅁㅇㄴ'ㄻㅇㄴ람;ㅣㅓㅇㄹUserDto  4 

 

 

 

ㅇㄴㄹㅇ

 

UserDto 클래스는 4개의 필드, 2개의 생성자, 9개의 메소드(getter/setter)라는 속성을 가지고 있는 클래스로 정의된다. 여기서 한 단계 더 높은 개념으로 생각해보면, 클래스라는 것 자체도 필드, 생성자, 메소드 등의 속성을 가지고 있다.

즉, Class 클래스는 이러한 클래스의 구조 자체를 하나의 클래스로 표현해놓은 클래스이다.

 

반환형인, Field, Method, Package, Constructor 등 모두 reflect 패키지에서 제공해주는 클래스들이다.

이렇듯 리플렉션을 통해 클래스의 정보를 알아내기 위한 기점에는 Class 클래스가 있는 것이다.

 

이제 위에서 작성한 UserDto 클래스에 리플렉션을 통해 정보를 뽑아내겠다.

먼저 UserDto 클래스를 Class 객체로 뽑아내야 하는데..

Class.forName("패키지 전체 경로") 또는 클래스이름.class

위의 형태로 호출하게 되면 해당 클래스의 정보를 담은 Class 클래스가 반환된다.

 

package reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Main {

	public static void main(String[] args) throws ClassNotFoundException {
		Class user = Class.forName("reflection.UserDto");	// UserDto.class도 가능
		
		System.out.println("====Field List====");
		
		for(Field field : user.getFields()) {
			System.out.println(field.getName());
		}
		
		System.out.println("\n==== Constructor ====");
		
		for(Constructor constructor : user.getConstructors()) {
			System.out.println("개수 : " + constructor.getParameterCount() + " = ");
			
			for(Class parameter : constructor.getParameterTypes()) {
				System.out.println(parameter.getName() + " / ");
			}
			
			System.out.println();
		}
		
		System.out.println("\n==== Method List ====");
		
		for(Method method : user.getMethods()) {
			System.out.println(method.getName());
		}
	}
}

 

출처:

joont.tistory.com/165

'자바' 카테고리의 다른 글

Spring Bean의 개념과 Bean Scope 종류  (0) 2020.11.12
영속성  (0) 2020.11.12
정규식  (0) 2020.11.11
synchronized  (0) 2020.11.09
람다  (0) 2020.11.09