type information - Generic Class References

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: 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

Guess you like

Origin blog.csdn.net/wangbingfengf98/article/details/96777508