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

what's the usecase for int.class, double.class?

我理解 class 文字和 getClass() 方法如何帮助泛型和反射,但我不明白为什么同样适用于原语?

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

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

有什么想法吗?

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

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也可以使用。)


You cannot instantiate via int.class.newInstance(), it will throw an Exception

那是因为newInstance() returns一个Object,原始值不能是对象。但是,请考虑:

    SomeType.class.newInstance()

等同于

    new SomeType()

现在考虑 Java 不会让您使用 new 来创建原始值。 (如果确实如此……您期望 new int 的实际值是多少?)


You cannot use them with generics since those require non-primitives.

没错,但正交。你写 List<MyClass>,而不是 List<MyClass.class>。 Class 不讨论文字。