[英]why casting double to int is possible but casting double to String is not possible?
[英]Why it's possible to instantiate String and not possible for Number(Long,Double,Integer…)?
嗨,為什么它可以實例化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會調用默認構造函數。 雙人沒有。
如果你想使用反射進行實例化,那么你必須使用Class。#getConstructor通過傳遞適當的參數類型來獲取類的一個Contructors ,然后通過傳遞適當的參數來調用它的方法Constructor#newInstance 。
java.lang.String
有一個空構造函數(調用new String()
與調用new String("")
)相同。
另一方面,數字沒有no-arg構造函數(無論如何new Double()
的值是什么?沒有相當於“空數”),因此不能以這種方式調用,甚至不是通過反思。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.