[英]What is the difference between the class `Class` and the class `Type` in java?
I've read this SO question that talks about the difference between classes and types in java 我读过这个SO问题 ,它讨论Java中类和类型之间的区别
However, this talks about classes declared with the class
keyword rather than the actual class Class
in java. 但是,这里讨论的是使用
class
关键字声明的class
而不是Java中的实际类Class
。 In Java, I can have a Class<T>
where T is a class/interface/array type (and for primitives, T
would be the autoboxed class, but the instance of Class<T>
would be associated with the primitive type, such as int.class). 在Java中,我可以具有
Class<T>
,其中T是类/接口/数组类型(对于基元, T
是自动装箱的类,但是Class<T>
的实例将与基元类型相关联,例如作为int.class)。 Point is, Class
is used with more than just class types. 重点是,
Class
不仅仅用于类类型。
What is the difference between the class Class
and interface Type
? class
Class
和interface Type
什么区别? When would I ever use Type
in a java program? 我什么时候可以在Java程序中使用
Type
?
Type
is a superinterface of Class
. Type
是Class
的超级接口。 You won't generally need to use it unless you're doing reflection with generic types. 除非对泛型类型进行反射,否则通常不需要使用它。
As an example, we can get the type of a field using Field.getType()
: 例如,我们可以使用
Field.getType()
获得字段的类型:
Class<?> c =
String.class.getField("CASE_INSENSITIVE_ORDER")
.getType();
The problem is that String.CASE_INSENSITIVE_ORDER
is actually a Comparator<String>
, and the above code will only get us Comparator.class
. 问题是
String.CASE_INSENSITIVE_ORDER
实际上是Comparator<String>
,并且上面的代码只会给我们Comparator.class
。 This doesn't work for us if we needed to know what the type argument was. 如果我们需要知道类型参数是什么,这对我们不起作用。
Type
and its uses were added in Java 1.5 (along with generics) for this type of situation. 在Java 1.5(以及泛型)中针对此类情况添加了
Type
及其用途 。 We could instead use the method Field.getGenericType()
: 我们可以改用
Field.getGenericType()
方法:
Type t =
String.class.getField("CASE_INSENSITIVE_ORDER")
.getGenericType();
In this case, it would return an instance of ParameterizedType
, with Comparator.class
as its raw type and String.class
in its type arguments: 在这种情况下,它将返回
ParameterizedType
的实例,其中Comparator.class
是其原始类型,而String.class
的类型参数是:
ParameterizedType pt = (ParameterizedType) t;
pt.getRawType(); // interface java.util.Comparator
pt.getActualTypeArguments(); // [class java.lang.String]
This part of the API isn't very well developed, but there are some better ones built around it, like Guava TypeToken
. API的这一部分开发不够完善,但是围绕它构建了一些更好的API,例如Guava
TypeToken
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.