簡體   English   中英

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

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM