简体   繁体   English

为什么可以实例化String而不可能为Number(Long,Double,Integer ...)?

[英]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.

相关问题 为什么可以将double转换为int,但是不能将double转换为String? - why casting double to int is possible but casting double to String is not possible? 为什么将String转换为double可能会失去精度? - Why is there a possible loss of precision converting a String to double? 用于将数字表示为String,Integer.java的所有可能的字符 - All possible chars for representing a number as a String, Integer.java 是带有单个参数的 Java 方法来接收两个 HashMap 的值吗<String, Integer>和 HashMap<Long, Integer> 可能的? - Is Java method with a single argument to receive values of both HashMap<String, Integer> and HashMap<Long, Integer> possible? 为什么无法致电列表 <Number> 不与列表 <Integer> 即使整数扩展了数字? - Why is it not possible to call List<Number> not with List<Integer> even if Integer extends Number? 如何向期望两倍的二传手提供Integer? - How is it possible to supply Integer to setter expecting double? 如何将double添加到Integer的ArrayList中? (JAVA) - How is it possible to add a double into an ArrayList of Integer? (Java) 在浇铸之前尽可能长地使用两倍? - Use double as long as possible before casting to float? 我想用一个数字(双精度或整数)表示图像中像素的位置。 有什么办法吗? - I want to represent the location of pixel in image by a single number(either double or integer). Is there any possible way? 将字符串转换为整数成员,可能吗? - Casting string as a integer member, possible?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM