简体   繁体   English

java中的Class和Class类型有什么区别?

[英]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 . TypeClass的超级接口。 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM