관리 메뉴

IT 쟁이

자바 리플렉션 본문

JAVA/Basic

자바 리플렉션

클라인STR 2011. 4. 3. 12:46

리플랙션 - 객체를 통해 클래스의 정보를 분석해내는 프로그램기법
리플렉션을 사용하는 이유는 형을 복원할수 없는 객체가 존재할 때 형을 확인하고, 객체를 생성하고 멤버 메서드 까지 호출할 수 있는 프로그램 기법이다.


Class 클래스
* .class 등록정보 클래스
* 바이트 코드의 등록정보 클래스
Class 클래스를 이용하여 클래스의 정보 추출하기
Class c = Hello.class
Class [] iface = c.getInterfaces();    //클래스에 포함된 인터페이스 알아내기
Class sc = c.getSupperclass()   // 클래스에 포함된 상위 클래스 알아내기

Method [] m = c.getMethods(); //클래스에 포함된 메서드 알아내기
Method m = c.getMethod("sayHello", null); //메소드 찾기
m.invoke(obj, null); //메소드 호출하기

Field [] f = c.getFields(); // 클래스 내에 포함된 필드 알아내기
Field f = c.getField("addr");
f.set(obj, "창원");
Object x = f.get(obj);

Constructor [] cs = c.getConstructors();
 
리플렉션 예제 )
Hellow.java
package com.hello;

public class Hellow {

	private String message;
	
	public Hellow() {

	}
	
	
	public String getMessage() {
		return message;
	}


	public void setMessage(String message) {
		this.message = message;
	}


	public void sayHello() {
		System.out.println("Hellow  "+message);
	}
}

DynyLoad.java
package com.hello;

import java.lang.reflect.*;

public class DynyLoad {

		
	public static void main(String[] args) throws Exception {	

		try {
			Class c = Class.forName("com.hello.Hellow");
			Object obj = c.newInstance();
			Object[] param  = new Object[]{"Hello"};
			Method m =c.getDeclaredMethod("setMessage",String.class);
			m.invoke(obj, param);			
			m = c.getDeclaredMethod("sayHello");
			m.invoke(obj);
			
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}

참조 : 소설같은 자바 http://www.jabook.com/
Comments