Java 反射測試

醉面韋陀發表於2010-08-10
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Java 反射測試
 * 
 * @author Administrator
 * 
 */

public class ReflectTest {

	/**
	 * For the test of method :getAllMethodList()
	 * 
	 * @param obj
	 * @param x
	 * @return
	 * @throws NullPointerException
	 */
	private ReflectTest testMethod(Object obj, int x)
			throws NullPointerException {
		if (obj == null)
			throw new NullPointerException();
		return new ReflectTest();
	}

	/**
	 * 獲取類中所有的方法列表 方法名稱、行參型別、異常型別、返回值型別
	 */
	private void getAllMethodList(Class c) {

		Method methlist[] = c.getDeclaredMethods();// c.getMethods()可獲取繼承來的所有方法
		for (int i = 0; i < methlist.length; i++) {

			Method m = methlist[i];
			System.out.println("name = " + m.getName());// 方法名
			System.out.println("declaring  class = " + m.getDeclaringClass());// 所在的類

			Class pvec[] = m.getParameterTypes();// 取得方法的形參型別
			for (int j = 0; j < pvec.length; j++)
				System.out.println("param #" + j + " " + pvec[j]);

			Class evec[] = m.getExceptionTypes();// 取得方法丟擲的異常物件型別
			for (int j = 0; j < evec.length; j++)
				System.out.println("exc #" + j + " " + evec[j]);

			System.out.println("return type = " + m.getReturnType());// 取得方法返回值的型別
			System.out.println("-----");
		}
	}

	/**
	 * For the test of method "excuteMethodByMethodName"
	 * 
	 * @param a
	 * @param b
	 * @return
	 */
	public int add(int a, int b) {
		return a + b;
	}

	/**
	 * 動態呼叫方法
	 * 
	 * @param c
	 * @return
	 */
	public Integer excuteMethodByMethodName(Class c, ReflectTest rt) {

		Object resultObj = null;// 儲存結果物件
		Method md = null;

		Class[] ptpyes = new Class[2];// 預定義要被呼叫的方法引數列表
		ptpyes[0] = Integer.TYPE;
		ptpyes[1] = Integer.TYPE;

		try {
			md = c.getMethod("add", ptpyes);// add是要被呼叫的方法名;通過行參ptpyes定位到具體哪個方法被呼叫(考慮多型的情況)
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}

		Object[] argus = new Object[2];// argus是傳給被呼叫方法的實參
		argus[0] = new Integer(22);
		argus[1] = new Integer(33);

		try {
			// 通過Method md 定位要被呼叫的方法名;
			// 通過ReflectTest rt 定位要被呼叫的方法所在的類;
			// 通過Object[] argus 將實參傳遞給被呼叫的方法
			resultObj = md.invoke(rt, argus);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		Integer result = (Integer) resultObj;
		return result;
	}

	public static void main(String args[]) {
		Class c = null;
		try {
			c = Class.forName("com.isoftstone.test.ReflectTest");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		ReflectTest rt = new ReflectTest();
		rt.getAllMethodList(c);
		Integer itg = rt.excuteMethodByMethodName(c, rt);
		System.out.println(itg.intValue());
	}

}

 

相關文章