Why is it possible to instantiate a String and not possible for Number (Long, Double, Integer ...)?

Hi, why is it possible to instantiate a String and not possible for Numbers. I made an example for this

public static void main(String[] args) throws InstantiationException, IllegalAccessException { String a = "s"; String newInstance = a.getClass().newInstance(); System.out.println(newInstance); Double b = 0d; Double newInstance2 = b.getClass().newInstance(); System.out.println(newInstance2); } 
+6
source share
2 answers

A call to newInstace calls the default constructor. Double does not exist.

If you want to instantiate using reflection, you need to get one of the Class Contractors using Class. # getConstructor , passing it the corresponding argument types, and then call its constructor method # newInstance , passing it the corresponding arguments.

+12
source

java.lang.String has an empty constructor (calling new String() same as calling new String("") ).
On the other hand, numbers have no constructors without arguments (whatever the value of a new Double() , that is, there is no equivalent to an "empty number") and, therefore, cannot be called in this way, not even by reflection.

+4
source

All Articles