[英]Why it's possible to instantiate String and not possible for Number(Long,Double,Integer…)?
Hi why it's possible to instantiate String and not possible for Numbers .I have made an example for that 嗨,为什么它可以实例化String而不是Numbers。我已经为此做了一个例子
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);
}
Calling newInstace invokes the default constructor. 调用newInstace会调用默认构造函数。 Double does not have one. 双人没有。
If you want to instantiate using reflection then you have to get one of the Contructors of the class using Class.#getConstructor by passing it the appropriate argument types and then call its method Constructor#newInstance by passing it the appropriate arguments. 如果你想使用反射进行实例化,那么你必须使用Class。#getConstructor通过传递适当的参数类型来获取类的一个Contructors ,然后通过传递适当的参数来调用它的方法Constructor#newInstance 。
java.lang.String
has an empty constructor (calling new String()
is the same as calling new String("")
). java.lang.String
有一个空构造函数(调用new String()
与调用new String("")
)相同。
Numbers, on the other hand, don't have no-arg constructors (what would the value of a new Double()
be anyway? there is no equivalent to an "empty number"), and thus can't be invoked this way, even not by reflection. 另一方面,数字没有no-arg构造函数(无论如何new Double()
的值是什么?没有相当于“空数”),因此不能以这种方式调用,甚至不是通过反思。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.