java 通过方法名称调用方法,为大量变量赋值,获取变量值

 

 

package my; 
import java.lang.reflect.InvocationTargetException; 
import java.lang.reflect.Method; 
//此例子使用情景:
//set(String methodname,String value)为大量String(可根据实际情况修改)类型的变量赋值,
//get(String methodname)获取变量值
//通过方法名称调用方法
public class Reflect {
        //要赋值的变量所在的类
	private Object obj;
	public Reflect(Object obj){
		this.obj=obj;
	}

        //method为方法名,value为传入参数(根据自己实际情况做修改)
	public void set(String methodname,String value){
		try {
                       //获取方法
			Method m=obj.getClass().getDeclaredMethod(methodname, String.class);
                       //调用方法(value根据自己实际情况做修改)
			m.invoke(obj, value);
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public String get(String methodname){
		String value=null;
		try {
			Method m=obj.getClass().getMethod(methodname);
			value=(String) m.invoke(obj);
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return value;
		
	}
}

 

 

 

你可能感兴趣的:(java 通过方法名称调用方法,为大量变量赋值,获取变量值)