본문 바로가기

심오한 세상/Java; Java FX;

클래스 이름을 이용하여 클래스를 생성하는 방법

기존의 우리가 클래스는 생성하는 방법은
아래와 같이, new 연산자를 이용하여 생성자를 호출하는 방식으로 했었다..

ExampleClass name = new ExampleClass();

하지만, 내가 무지한 탓인지...
클래스 이름을 String 값으로 가지고 있어도 클래스를 생성할 수 있다는 사실을 알게되었다.
아래와 같이 클래스 이름만 가지고 있다면...

String name = "ExampleClass";

Class 클래스에 있는 forName() 메소드를 사용함으로써 ExampleClass라고 하는 클래스가 초기화가 된다.

Class t = Class.forName(name);

객체 t를 이용하여 새로운 객체를 생성하게 된다.

name = (ExampleClass) t.newInstance();

(Example)
HTTPServerSocket server = new HTTPServerSocket(port);
위의 것을 클래스 이름만 알고 있다면 아래와 같이 바꿔서 생성할 수 있다.

String serverClass = "context.arch.comm.protocol.HTTPServerSocket";
int serverPort = 6000;

Class[] classes = new Class[2];
classes[0] = Class.forName("context.arch.comm.CommunicationsObject");
classes[1] = Class.forName("java.lang.Integer");

Constructor constructor = Class.forName(serverClass).getConstructor(classes);

Object[] objects = new Object[2];
objects[0] = this;
objects[1] = new Integer(serverPort);

server = (CommunicationsServer)constructor.newInstance(objects);

p.s.
클래스 이름만 알고 있는 상태에서 저렇게 한다면 클래스를 쉽게 생성할 수 있다.
프로그래밍을 하다보면 클래스 이름을 이용해서 객체를 생성해야할 때 저렇게 사용해보는 것은 어떨까?

Chan이 준 사용 예이다. ㅋㅋ
이게 command 패턴이라고 한다.

String action = getAction();
IAction = null;
if ( action != null ) {
   IAction tempAction = ( IAction ) Class.forName(action).getConstructor().newInstance();
   tempAction.doAction();
}