1. 程式人生 > >一個反射的例子

一個反射的例子


public class Father {
	
	public Father(){
		System.out.println("con father");
	}

	public void fatherMethod(String name){
		
		try {
			Class<? extends Father> clazz = this.getClass();
			Method method = clazz.getDeclaredMethod(name);
			method.invoke(this);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}

public class Son extends Father {
	
	public Son(){
		System.out.println("con son");
	}
	
	public void son1(){
		System.out.println("son11");
	}
	
	public void son2(){
		System.out.println("son22");
	}

}

public class Test {
	
	public static void main(String[] args){
		
		/*Son son = new Son();
		son.fatherMethod("son1");*/
		
		Father father = new Son();
		father.fatherMethod("son1");
		
	}
}

通過傳遞方法名就可以呼叫相應的方法,不用再寫if判斷了。