티스토리 뷰

문자열로 클래스를 만들기 위해서는 java.lang.Class.forName() 을 사용할 수 있다.

우선, Class.forName()의 정의는 이렇다.



 The java.lang.Class.forName(String namemethod returns the Class object associated with the class or interface with the given string name.

The java.lang.Class.forName(String name, boolean initialize, ClassLoader loader) method returns the Class object associated with the class or interface with the given string name, using the given class loader.


사용해 보기 앞에 forName()을 왜 사용할까? forName()을 사용하면, String 타입의 값으로만으로 클래스를 생성할 수 있다. 즉,  스트링 값에 따라 자동으로 생성되는 코드를 생성할 수 있기때문에 코드가 유연해진다.

[ forName()을 이용해서 클래스를 생성하기 ]

public class A {
	public A() {
		System.out.println("A가 생성되었습니다.");
	}

	public void show(boolean showOK){ 
		if (showOK)
			System.out.println("A 출력");
	}
	
	static{
		System.out.println("난 static블럭에 있는 함수");
	}
}

다음과 같은 클래스가 있다. 이를 forName() 을 사용해서 만들어보자.


 


public class test {

	public static void main(String[] args) {

		String Testclass = "com.SIM.pack1.A";

		try {
			Class<?> testClass = Class.forName(Testclass); 

		} catch (Exception e) {
		} 
	}
}

이 코드는 현재 forName()만을 사용한 코드이다. forName()으로 클래스를 받아오는 과정이다. 이때, 클래스가 생성은 되지 않는다. 하지만, 출력해보면 알겠지만, static 블럭의 내용을 실행하는 것을 볼 수 있다. 바로 다음으로 클래스를 생성하여, 함수까지 호출해보자.
public class test {

	public static void main(String[] args) {

		String Testclass = "com.SIM.pack1.A";

		try {
			Class<?> testClass = Class.forName(Testclass);
			Object newObj = testClass.newInstance();
			Method m = testClass.getDeclaredMethod("show", boolean.class);
			m.invoke(newObj, true);

		} catch (Exception e) {	
		}

	}
}

다음 코드에서 Class의 newInstance()함수를 볼 수 있다. 이는 클래스의 받아온 정보를 기반으로 객체를 생성하는 함수이다. 또한, 그 아래 줄은 메소드를 실행하기 위해서 해당 클래스내의 정의 되어있는 메소드를 불러와 호출하는 과정이다. .getDeclaredMethod()라는 함수를 통해 메소드를 받고, invoke()를 통해 호출 할 수 있는데, 인자값의 수를 알 수 없으므로, getDeclaredMethod()와 invoke()의 두번째 매개변수는 가변매개변수로 구현되어있다.


forName()을 사용하는데, properties를 사용할 수 도 있다.

http://sks3297.tistory.com/75


'Language > Java' 카테고리의 다른 글

[JAVA] Checked or Unchecked Exceptions  (0) 2013.11.19
[JAVA] properties사용하기  (0) 2013.11.05
[JAVA] MySql연동  (0) 2013.10.24
[JAVA] String, StringBuilder, StringBuffer의 문자열 합  (0) 2013.10.21
[JAVA] System.gc()  (0) 2013.10.21
댓글
최근에 올라온 글
최근에 달린 댓글
글 보관함
Total
Today
Yesterday