我正在尝试创建一个函数,该函数将调用给定一组参数的类的构造函数 封装 testytest;
import java.lang.reflect.Constructor;
public class MainClass {
public static <T> T newClass(Class<?> inst, Object ... args){
@SuppressWarnings("unchecked")
Constructor<?> [] ctor = (inst.getDeclaredConstructors());
int argIndex = 0;
ctorLoop: for(Constructor<?> x : ctor){
argIndex = 0;
for(Class<?> s : x.getParameterTypes()){
if(argIndex > args.length || args[argIndex++].getClass() != s){
if(argIndex <= args.length)
System.out.println("Param doesnt match : " + args[argIndex-1].getClass() + " with " + s);
continue ctorLoop;
}
}
try{
return (T)x.newInstance(args);
}catch(Exception e){
System.err.println("Error in instantiating instance of class : " + inst);
return null;
}
}
System.err.println("No instance of constructor found for class " + inst);
return null;
}
public static void main(String[] args) {
System.out.println(newClass(Double.class,5.0));
}
}
这给了我错误
Param doesnt match : class java.lang.Double with double
Param doesnt match : class java.lang.Double with class java.lang.String
No instance of constructor found for class class java.lang.Double
看线
Param doesnt match : class java.lang.Double with double
有没有一种方法可以本地进行 boolean 匹配,而无需交换每个 native 类型( double 、浮点、长整型、整数等?)的大小写?
最佳答案
包装类中定义了一些常量,这些常量表示基本类型的 Class
对象。对于double
,使用Double.TYPE
.
The
Class
instance representing the primitive typedouble
.
这应该与您正在查找的构造函数的假定 double
参数相匹配。
其他基元的其他示例有 Integer.TYPE
、Float.TYPE
、Short.TYPE
、Byte.TYPE
、Long.TYPE
、Character.TYPE
和 Boolean.TYPE
。甚至还有用于 void
的 Void.TYPE
。
关于java - 自动将数字对象转换为其 native 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27934392/