type information - Generic Class References

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/wangbingfengf98/article/details/96777508

A Class reference points to a Class object, which manufactures instances of classes and contains all the method code for those instances. It also contains the statics for that class. So a Class reference really does indicate the exact type of what it’s pointing to: an object of the class Class.

However, the Java designers saw an opportunity to make this a bit more specific by allowing we to constrain the type of Class object to which the Class reference points, using the generic syntax. In the following example, both syntaxes are correct:

// typeinfo/GenericClassReferences.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

public class GenericClassReferences {
  public static void main(String[] args) {
    Class intClass = int.class;
    // generic syntax allows the compiler to enforce extra type checking.
    Class<Integer> genericIntClass = int.class;
    genericIntClass = Integer.class; // Same thing
    intClass = double.class;
    // genericIntClass = double.class; // [1] Illegal
  }
}

When uncomment [1], it prompts bellow error

typeinfo/GenericClassReferences.java:12: error: incompatible types: Class<Double> cannot be converted to Class<Integer
>
    genericIntClass = double.class; // [1] Illegal
                            ^
1 error

references:

1. On Java 8 - Bruce Eckel

2. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/typeinfo/GenericClassReferences.java

猜你喜欢

转载自blog.csdn.net/wangbingfengf98/article/details/96777508
今日推荐