int.class,double.class的用例是什么?

时间:2019-02-13 11:15:19

标签: java generics reflection primitive

我了解类文字和getClass()方法如何帮助它们进行泛型和反射,但是我不明白为什么同样适用于原语?

例如,对于int而言,我可以使用int.class,但不确定您能做什么。

  1. 您无法通过int.class.newInstance()实例化,它会抛出Exception
  2. 您不能将它们与泛型一起使用,因为它们需要非基元

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

这是一个例子。假设您有一个带有重载原始参数方法的类;例如

public class Test {
    public void test(int a) { .... }
    public void test(char a) { .... }
}

如何为Method方法之一反思地获得test对象?答案:通过致电(例如):

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>。类文字不参与讨论。

相关问题