mardi 13 janvier 2015

Automatic conversion of numeric objects to their natives

I'm trying to make a function that will invoke the constructor of a class given a set of arguments 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));

}

}


which gives me the error



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


looking at the line



Param doesnt match : class java.lang.Double with double


is there a way to natively make this boolean match without case swapping every native type (double,float,long,int,etc?)






Aucun commentaire:

Enregistrer un commentaire