You could check the type and create a new integer:
if(cls == Integer.class) return Integer.valueOf(0);
or
if(cls == Integer.class) {
return cls.getConstructor(int.class).newInstance(0);
}
However this method would still return an object, not an instance of Integer
.
A better option could be something like:
static <T extends Number> T newNumber1(Class<T> tClass, String s){
if(tClass == Integer.class){
return (T) Integer.valueOf(s);
}
}
// OR
static Number newNumber2(Class<? extends Number> tClass, String s){
if(tClass == Integer.class){
return Integer.valueOf(s);
}
}
Usage:
int v1 = newNumber1(Integer.class, "5");
int v2 = newNumber2(Integer.class, "6").intValue();
UPDATE:
static <T> T newInstance(Class<T> tClass, String s) throws Exception{
return tClass.getConstructor(String.class).newInstance(s);
}
public static void main(String[] args) throws Exception{
Double d = newInstance(Double.class, "4");
System.out.println(d);
}