利用反射实现动态方法调用

package test.my.chap0302;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class MethodTest {

	/**
	 * @param args
	 * @throws NoSuchMethodException 
	 * @throws SecurityException 
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 * @throws IllegalArgumentException 
	 */
	public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
		
		//利用反射实现动态方法调用
		Method sin = Math.class.getDeclaredMethod("sin",Double.TYPE);
		System.out.println(sin);
		Double d = (Double)sin.invoke(null,new Integer(2));
		System.out.println(d);
		Method str = String.class.getDeclaredMethod("equals",Object.class);
		Boolean bl = (Boolean) str.invoke(new String("利用反射实现动态调用方法"),"利用反射实现动态调用方法");
		System.out.println(bl);
	}

}

posted on 2015-03-29 17:21  Msea  阅读(148)  评论(0编辑  收藏  举报

导航