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;
}
我应该怎么获得并判断参数的类型?谢谢!!~
本文介绍了一种使用Java反射机制来实例化特定类对象的方法。该方法通过传递类名和参数来选择合适的构造函数,并创建实例。文章还讨论了如何处理多个具有相同参数数量但类型不同的构造函数的情况。
16万+

被折叠的 条评论
为什么被折叠?



