본문 바로가기
JAVA/자바의 클래스

Class클래스로 가져온 클래스 정보 사용법.(feat.리플렉션 프로그래밍)

by 김꾸꾸(하트) 2022. 11. 22.

     리플렉션 프로그래밍 (잘 사용x)     

정의

Class클래스를 이용해서 해당 클래스의 정보를 가져오고

그 정보를 활용해서 인스턴스를 생성하거나 메서드를 호출하는 방식

( 클래스의 이름만 알아도 클래스의 생성자, 메서드 등의 정보를 알 수 있음 )

 

 

 

 

 

     getConstructors()메서드     

정의

모든 생성자를 가져오는 메서드

 

 

 

     getFields()메서드     

정의

모든 멤버 변수(필드)를 가져오는 메서드

 

 

 

     getMethods()메서드     

정의

모든 메서드를 가져오는 메서드

 

 

 

예제

package ch04UseClass;

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

//오늘 배운 내용 - Class클래스로 가져온 클래스 정보 사용법.(리플렉션 프로그래밍)
public class StringClassTest {
	public static void main(String[] args) throws ClassNotFoundException {

		Class strClass = Class.forName("ch04bringClass.Person");//클래스 이름으로 가져오기
		
		Constructor[] cons = strClass.getConstructors();//Person클래스의 모든 생성자 가져오기
		for(Constructor c : cons ) {//향상된 for문이용해서 생성자 전부 출력.
			System.out.println(c);
			//String자료형은 java.lang.String으로 뜸.
		}
		
		System.out.println(); 
		Field[] fields = strClass.getFields();//Person클래스의 모든 멤버변수 가져오기
		for(Field f : fields) {//향상된 for문이용해서 멤버변수 전부 출력.
			System.out.println(f);
		}
		
		System.out.println();
		Method[] method = strClass.getMethods();//Person클래스의 모든 메서드 가져오기
		for(Method m : method) {//향상된 for문이용해서 메서드 전부 출력.
			System.out.println(m);
			//모든 클래스의 최상위 클래스인 Object클래스의 메서드들도 불러옴.
		}
		

		
	}
}

 

 

 

 

 

 

 

출처 - Do it! 자바 프로그래밍 입문 (박은종 선생님)

https://www.aladin.co.kr/shop/wproduct.aspx?ItemId=157852460