6
回答
Java反射通过类名字符串创建实例(带参数并判断参数类型)
华为云4核8G,高性能云服务器,免费试用   
private Object newObjectInstanceWithParams(String classname, Object[] params) {
    	Object instance = null;
    	try {
			Class classType = Class.forName(classname);
			
			Constructor<?>[] consts = classType.getConstructors();
	        Constructor<?> constructor = null;
	        for(int i = 0; i < consts.length; i++) {
	        	int paramsLength = consts[i].getParameterAnnotations().length;
	        	//判断多少个参数,我想在这添加参数的类型,因为有一个类的2个构造函数都要2个参,但是类型不同
	        	if(paramsLength == params.length) {
	        		constructor = consts[i];
	        		break;
	        	}
	        }
	        
	        if(constructor != null) {
	        	Class<?>[] type = constructor.getParameterTypes();
	        	instance = classType.getConstructor(type).newInstance(params);
	        }
			
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    	return instance;
    }

我应该怎么获得并判断参数的类型?谢谢!!~


举报
Jian_Ming
发帖于3年前 6回/2K+阅
顶部