티스토리 뷰

카테고리 없음

[Java]동적 Class Loading

out of coding 2015. 1. 21. 12:19

자신이 알고 있는 클래스를 가져다가 바로 생성할수 있는데,

동적으로 사용하게 되면, 코드를 유연하게 할수 있다.


클래스의 이름은 풀패키지를 사용하도록 하고,

아래는 예를 위하여 메인클래스에서 호출하여서 사용하도록 하였다.


다음은 동적으로 로딩하는 소스이다.


public class Main {

	public static void main(String[] args) {

		String className = "com.mrgamza.Main";

		try {
			Class<?> clazz = Class.forName(className);
			Object object = clazz.newInstance();

			Method method_getBoolean = clazz.getDeclaredMethod("getBoolean");
			boolean getBoolean = (Boolean)method_getBoolean.invoke(object);
			System.out.println("getBoolean() : " + getBoolean);

			Method method_getString = clazz.getDeclaredMethod("getString", String.class);
			String getString = (String)method_getString.invoke(object, "mrgamza");
			System.out.println("getString() : " + getString);

			Method method_sum = clazz.getDeclaredMethod("sum", new Class[]{int.class, int.class});
			int sum = (Integer)method_sum.invoke(object, 10, 21);
			System.out.println("sum() : " + sum);
		} catch(Exception e) {
			System.out.println("exception : " + e.getMessage());
		}
	}

	public boolean getBoolean() {

		return true;
	}

	public String getString(String input) {

		return "result=" + input;
	}

	public int sum(int a, int b) {

		return a + b;
	}
}

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함