反射(Reflection)

1401 ワード


class A {
	public void method() {
			System.out.println("A's method is running.");;
	}
}

class B {
	public void method() {
		System.out.println("B's method is running.");;
	}
}

class Factory {
	@SuppressWarnings("unchecked")
	public static <T> T getInstance(String className) {
		T instatnce = null;
		try {
			Class<?> c = Class.forName(className);
			instatnce = (T) c.newInstance();
		} catch (ClassNotFoundException e) {			
			e.printStackTrace();
		} catch (InstantiationException e) {			
			e.printStackTrace();
		} catch (IllegalAccessException e) {			
			e.printStackTrace();
		} 
		return instatnce;		
	}
	
	public static <T> T getInstance(Class<T> c) {
		T instance = null;
		try {
			instance = c.newInstance();
		} catch (InstantiationException e) {			
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return instance;		
	}
}

class Main {
	public static void main(String[] args) {
		A a = Factory.getInstance("A");
		a.method();
		B b = Factory.getInstance(B.class);
		b.method();
	}
}