天天看點

調用反射類的指定方法

package org.entity;

import java.lang.reflect.Method;


/**
 * 本案例示範如何通過反射将字元串轉換為類
 * */
public class Test2_2 {
  
	public static void main(String[] args) {
		String user = "org.entity.User";//字元串是該類的全限定名
			try {
				Class clzz = Class.forName(user);
				Object classObj=clzz.newInstance();//将class類轉換為對象
				//--------------------反射類調用User中的sayHello()方法-----------------------------
				//注意導入正确的Method包名:
				// import java.lang.reflect.Method;
				//參數是String
					Method method = clzz.getMethod("sayHello",String.class);
					method.invoke(classObj, "Hello wold");
				//參數是其餘基本資料類型
				/*Method method = clzz.getMethod("sayHello",int.class);
				method.invoke(classObj, 52);*/
				//注入double類型Method method = clzz.getMethod("sayHello",double.class);
				/*Method method = clzz.getMethod("sayHello3",String[].class);
				String[] ss=new String[]{"1","2","3"};
				method.invoke(classObj, new Object[]{ss});*/
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			} 
		
	}

}