嗨,为什么可以实例化 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);
}
最佳答案
调用 newInstace调用默认构造函数。 Double没有。
如果您想使用反射进行实例化,那么您必须使用 Class.#getConstructor 获取该类的构造函数之一。通过将适当的参数类型传递给它,然后调用它的方法 Constructor#newInstance通过向其传递适当的参数。
关于java - 为什么可以实例化 String 而不能实例化 Number(Long,Double,Integer...)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20772895/