Java - 通过反射进行动态赋值以及函数调用

Teacher 类

public class Teacher {
    private int userId;
    private String userName;

    public int getUserId() {
        return userId;
    }

    public String getUserName() {
        return userName;
    }

    private void hello(String name, Integer userId) {
        System.out.println("Hello World," + name + ", " + userId);
    }
}

通过反射进行赋值

Field fieldName= xxx.class.getDeclaredField(“fieldName”);
fieldName.set(xxx,“值”);

Teacher teacher = new Teacher();
   Field userName = Teacher.class.getDeclaredField("userName");
   // 授权访问私有成员变量(如果字段是私有的,需要设置setAccessible(true)否则会报错)
   userName.setAccessible(true);
   userName.set(teacher, "ljj");

通过反射进行函数调用

Method method = xxx.class.getDeclaredMethod(方法名称, 参数类型1.class, 参数类型2.class,…);
method .invoke(xxx, 参数1,参数2);

Teacher teacher = new Teacher();
    // 写对方法名称、参数类型
    Method hello = Teacher.class.getDeclaredMethod("hello", String.class, Integer.class);
    // 因为是私有的,所以要想访问,需要设置Accessible
    hello.setAccessible(true);
    // 对应的参数
    Object[] objects = {"LJJ", 24};
    // 调用函数
    hello.invoke(teacher, objects);
    //hello.invoke(teacher, "LJJ", 24);
//不确定 反射方法的参数
Teacher teacher = new Teacher();
	Method method = Teacher.class.getDeclaredMethod("hello", String.class, Integer.class);
	Type[] argTypes = method.getGenericParameterTypes();
	Object[] args=new Object[argTypes.length];
	for(int i=0;i<args.length;i++){
		args[i]=TypeUtils.cast(params.get(i), argTypes[i], ParserConfig.getGlobalInstance());
	}
	Object data = method.invoke(service, args);

getMethod()和getDeclaredMethod() 区别

getMethod():获取自身能用所有的公共方法。1.类本身的public 2.继承父类的public 3.实现接口的public
getDeclaredMethod():获取类自身声明的所有方法

映射调用方法获取数据

var hgExport = function (type) {
	publicEcportFn(
		'xxx.power.xxxExportDTO',
		`xxx/年申报电量_${type}导出模板.xlsx`
	)
}
var publicEcportFn = function (url, fileName) {
	var modelConfig = {}
	modelConfig.serviceName =
		'xxx.context.IxxxContext'
	modelConfig.methodName = 'findListPageByParam'
	modelConfig.getParams = function () {
		var arr = [getSumColNames(), 1, 50000]
		return arr
	}
	var controlConfig = {}
	controlConfig.dtoName = url
	var viewConfig = {}
	viewConfig.templateName = fileName
	$('#eptbtn').excelexport(modelConfig, controlConfig, viewConfig)
}
public void exportExcelDispatch(final HttpServletRequest newReq, final HttpServletResponse newResp){

	Object data;
	try {
		data = getData(newReq);
	} catch (Exception e) {
		throw new RuntimeException("获取导出数据失败",e);
	}
}
private Object getData(final HttpServletRequest newReq) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException{
			String modelConfigStr = newReq.getParameter("modelConfig");
		Map<String, Object> modelConfig = null;
		if (!StringUtil.isEmptyString(modelConfigStr)) {
			Object json = JSON.parse(modelConfigStr);
			modelConfig = TypeUtils.cast(json, Map.class, ParserConfig.getGlobalInstance());
		}
		String serviceName = (String)modelConfig.get("serviceName");
		String methodName = (String)modelConfig.get("methodName");
		List<Object> params = (List<Object>)modelConfig.get("params");

		Object service = OSGiUtil.getService(serviceName);
		Method method = (Method)ClassUtil.getInstanceMethodMap(service.getClass()).get(methodName);
		//Method method = service.class.getDeclaredMethod(methodName, String.class, Integer.class);
		Type[] argTypes = method.getGenericParameterTypes();
		//JSONArray jsonArr=JSON.parseArray(params);
		Object[] args=new Object[argTypes.length];
		for(int i=0;i<args.length;i++){
			args[i]=TypeUtils.cast(params.get(i), argTypes[i], ParserConfig.getGlobalInstance());
		}
		Object data = method.invoke(service, args);
		return data;
	}

你可能感兴趣的:(java,开发语言)