关于java中method.invoked 传入类型不一样的问题

关于java中method.invoked 传入类型不一样的问题

前言

  • 最近在尝试写着自己的一些框架,其中遇到了一个比较麻烦的问题,就是mvc中,获取前端传来的参数后,需要辨别类型,一一对应传给method调用invoke方法,但是。其中invoke需要传入改方法对应类的class以及参数,object数组。当方法的传入参数都是string类型的时候没有任何的问题,但是,当其中一个为Integer类型的时候就会报错。然后自己另外写了点方法测试一下。

测试

package Test;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class TestMethod {
	
	public String string1 = "11111";
	public String string2 = "22222";
	public String string3 = "33333";
	public Integer integer1 = 111;

	
	public void setString1(String string1,String string2,String string3,Integer integer1) {
		System.out.println("进入 setString1");
		this.string1 = string1;
		this.string2 = string2;
		this.string3 = string3;
		this.integer1 = integer1;
		System.out.println("this.string1 :" + this.string1);
		System.out.println("this.string2 :" + this.string2);
		System.out.println("this.string3 :" + this.string3);
		System.out.println("this.integer1 :" + this.integer1);
	}
	
	

}

package TestMain;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import Test.TestMethod;

public class Main {
	
    
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException{
    	Class<?> clzz = Class.forName("Test.TestMethod");
    	clzz.getMethods();
    	Object[] objects = new Object[4];
    	TestMethod tsMethod = new TestMethod();
    	for(Method method : clzz.getMethods()){
    		
    		System.out.println(">>>>>>>method.getParameterCount()" + method.getParameterCount());
        	objects[0] = "1";
        	objects[1] = "2";
        	objects[2] = "3";
        	objects[3] = "1";
    		System.out.println("method name " + method.getName());
    		if("setString1".equals(method.getName()))
    		method.invoke(clzz.newInstance(),objects);
    	}
    	
    	
    }
	
	 

}


  • 测试结果如下,报错

在这里插入图片描述

  • 原因应该是在invoke下,应该不会对类型进行辨别和拆箱

在这里插入图片描述

上面改为如下

在这里插入图片描述

  • 运行成功
  • 在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/BeamCSDN/article/details/84556122