Study/WAS만들기

Reflection

ABCD 2023. 6. 6.

Reflection

  • Class 객체를 통해 클래스의 정보를 분석해 내는 프로그램 기법
  • 컴파일 과정에서 import한 파일을 의존하여 가져가지 않고, 런타임과정에서 해당 class의 소스를 읽는 방법
    • 현재 Class가 해당 Class를 의존하지 않고 사용할 때 해당 Class의 정보를 가져오는 방식
      • 의존

        → 해당 Class가 없으면 동작하지 않음

        → import를 해주어야 온전히 컴파일 되는 것(?)

사용방법

"class".class //로 가져오기
"인스턴스".getClass() //로 가져오기
Class.forName("클래스명") //으로 가져오기

예시

public static Class getInstance(String url){
	String propertiesPath = "path";
	Proerties properties = new Properties();
	File propertiesFile = new File(propertiesPath);
	Class obj;
	try {
		Reader reader = new FileReader(propertiesFile);
		properties.load(reader);
		obj = Class.forName(properies.getProperty(url);
	} catch (Exception e){
		throw new RuntimeException(e);
	}
	
	return obj;
}

참고사항

k=v
uri=class
/my=co.ulim.MyHandler
Properties properties = new Properties();
properties.load();
new co.ulim.MyHandler()
String className = properties.getProperty(uri);
Class handlerClass = Class.forName(className);
RequestHandler handler = (RequestHandler) handlerClass.getConstructor().newInstance(); // reflection
handler.hanlde();
RequestHandler handler = RequestHandlerFactory.getInstance(uri);
handler.hanlde(req, res);

Uploaded by N2T

728x90
반응형

'Study > WAS만들기' 카테고리의 다른 글

MIME-Type / Content-Type  (1) 2023.06.18
Thread / Runnable / Thread Pool  (1) 2023.06.11
Thread / Runnable  (0) 2023.06.11
Socket과 ServerSocket  (0) 2023.05.31

댓글

💲 추천 글