我試圖做一個函數,將調用給定一組參數的類的構造函數 package 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
是有辦法本身使這個布爾匹配不區分交換每本機類型(雙,浮法,long,int等?)