[英]what's the usecase for int.class, double.class?
我了解類文字和getClass()
方法如何幫助泛型和反射,但我不明白為什么同樣適用於原語?
例如,對於int,我可以使用int.class
但不確定您可以使用它做什么。
int.class.newInstance()
實例化,這將引發Exception
有任何想法嗎?
這是一個例子。 假設您有一個帶有重載原始參數方法的類; 例如
public class Test {
public void test(int a) { .... }
public void test(char a) { .... }
}
如何反思性地獲得Method
test
方法的Method
對象? 答:通過致電(例如):
Class<?> testClass = Test.class;
Method method = testClass.getDeclaredMethod("test", int.class);
(請注意,也可以使用Integer.TYPE
。)
您無法通過
int.class.newInstance()
實例化,這將引發Exception
這是因為newInstance()
返回一個Object
,並且原始值不能是一個對象。 而且,請考慮:
SomeType.class.newInstance()
相當於
new SomeType()
現在考慮Java不允許您使用new
來創建原始值。 (如果這樣做的話,您希望new int
的實際值是多少?)
您不能將它們與泛型一起使用,因為它們需要非基本體。
是的,但是是正交的。 您編寫List<MyClass>
,而不是List<MyClass.class>
。 類文字不參與討論。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.