Java generic -- erasure of all evil

Source: Internet
Author: User

I. Erasure of all evils I have mentioned in my self-Summary of [Java Experience Summary 3] Java Generics-I first learned about generics. This blog post mentioned the problem of generic erasure in Java, consider the following code: Copy code 1 import java. util. *; 2 public class ErasedTypeEquivalence {3 public static void main (String [] args) {4 Class c1 = new ArrayList <String> (). getClass (); 5 Class c2 = new ArrayList <Integer> (). getClass (); 6 System. out. println (c1 = c2); 7} 8}/* Output: 9 true 10 *///:~ Copy the code in lines 4th and 5th of the code. We define a List that accepts the String type and a List that accepts the Integer type respectively. According to our normal understanding, although the generic ArrayList <T> is the same, different type parameters are passed to it, so the c1 and 2 types should be different. However, the results are exactly the same. The running program finds that the two types are the same. Why? Here we will talk about the unique Java Implementation of generics-Erasure (all evil). That is, when we declare List <String> and List <Integer>, they are actually the same at runtime, all are List, and the specific type parameter information String and Integer are erased. This leads to a very troublesome problem: in generic code, you cannot obtain any information about generic parameter types (from Java programming idea 4th). In order to experience the "all evil" erased by all evil, we make a comparison with C ++: C ++ template: copy the Code 1 # include <iostream> 2 using namespace std; 3 template <class T> class Manipulator {4 T obj; 5 public: 6 Manipulator (T x) {obj = x;} 7 void manipulate () {obj. f () ;}8}; 9 class HasF {10 public: 11 void f () {cout <"HasF: f ()" <endl ;}12 }; 13 int main () {14 HasF hf; 15 Manipulator <HasF> manipulator (hf); 16 manipulator. manipulate (); 17}/* Output: 18 HasF: f () 19 ///:~ Copy the Code. In this code, we declare a template (generic) Class Manipulator. This class receives a T-type object and calls the f method of this object internally, in main, we pass in a class HasF with f methods to Manipulator, and then the code is compiled normally and runs smoothly. In C ++ code, there is actually a strange thing, that is, in line 2 of code, we use the incoming T-type object to call its f method, so how do I know if the T type parameter you passed in has a method f? But from the perspective of the entire compilation, C ++ does implement it and ensures the correctness of the entire code (an error will be reported if a class without method f can be verified ). As for how to do this, we will mention it later. OK. We will implement this code in Java: Java generic: Copy code 1 public class HasF {2 public void f () {System. out. println ("HasF. f () ");} 3} 4 class Manipulator <T> {5 private T obj; 6 public Manipulator (T x) {obj = x;} 7 // Error: cannot find symbol: method f (): 8 public void manipulate () {obj. f ();} 9} 10 public class Manipulation {11 public static void main (String [] args) {12 HasF hf = new HasF (); 13 Manipulator <HasF> Manipulator = 14 new Manipulator <HasF> (hf); 15 manipulator. manipulate (); 16} 17 }///:~ Copy the code and you will find that the effect we can easily achieve in C ++ cannot be achieved in Java, and an error message is displayed in line 7th of code, that is to say, inside the Manipulator, we cannot know whether the type T contains method f. Why? It is caused by the erasure of all evil. When Java code is running, it will erase the type information T of the generic class, that is, the runtime stage, the Generic Code does not know any information about the type parameter. As shown in the above Code, the type information of the Manipulator <HasF> class in the running phase will be erased, leaving only Mainipulator. Therefore, HasF does not know the input parameter type in Manipulator, therefore, the 8th-line code obj will naturally report an error when calling f (that is, I know if you have any f method). In summary, we can see the cost of Erasure: in generic classes or generic methods, we cannot obtain any type information. Therefore, generics cannot be used to display reference runtime type operations, for example, transformation, instanceof operation, and new expression. For example, run the following code: Copy code 1 public class Animal <T> {2 T a; 3 public Animal (T a) {4 this. a = a; 5} 6 // error! 7 public void animalMove () {8 a. move (); 9} 10 // error! 11 public void animalBark () {12 a. bark (); 13} 14 // error! 15 public void animalNew () {16 return new T (); 17} 18 // error! 19 public boolean isDog () {20 return T instanceof Dog; 21} 22} 23 public class Dog {24 public void move () {25 System. out. println ("dog move"); 26} 27 public void bark () {28 System. out. println ("wang! Wang !); 29} 30} 31 public static void main (String [] args) {32 Animal <Dog> ad = new Animal <Dog> (); 33} copy the code. We declare a generalized Animal class, and then declare a Dog class. The Dog class can move () and bark at bark (). In main, pass Dog as a type parameter to Animal <Dog>. In lines 8th and 11th of the code, we tried to call the moving () and bark () Functions of the incoming class and found an error. In line 16 of the Code, we try to return a new T-type object and get an error. In the 20 lines of code, when we try to use instanceof to determine whether T is of the Dog type, it is also an error! So as we said above: in generic code, you cannot obtain any information about generic parameter types (from Java programming idea 4th). when writing a generalization class, we should always remind ourselves that the input parameter T is only an Object type, and any specific type information is unknown. Ii. Why is Java erasure described in the above section A general erasure problem in Java, which also experiences all the evil and brings inconvenience to programming. Why are Java developers doing this? This is a historical issue. Java does not support generics in Version 1.0, which leads to a large batch of original class libraries created on Java versions that do not support generics. Later, Java gradually added generics. To enable the original non-generalized class library to be used on generalized clients, Java developers used erasure to compromise. Therefore, Java uses such a limited generic Implementation Method to transition from non-generalized code to generalized code, and integrate generics into the Java language without disrupting the original class library. Iii. How to Solve the troubles caused by erasure solution 1: Do not use the Java language. This is nonsense, but indeed, when you use python, C ++, and other languages, you will find that Using Generics in these two languages is very easy and casual, in Java, things are much more complicated. Example: python: Copy code 1 class Dog: 2 def speak (self): 3 print "ASON! "4 def sit (self): 5 print" Sitting "6 def reproduce (self): 7 pass 8 9 class Robot: 10 def speak (self): 11 print" Click! "12 def sit (self): 13 print" Clank! "14 def oilChange (self): 15 pass 16 17 def perform (anything): 18 anything. speak () 19 anything. sit () 20 21 a = Dog () 22 B = Robot () 23 perform (a) 24 perform (B) copy the code to use python generics is almost freehand, define two classes: Dog and Robot, and then directly declare a perform generic method using anything. In this generic method, we call the speak () and sit () of anything respectively () method. C ++ copy code 1 class Dog {2 public: 3 void speak () {} 4 void sit () {} 5 void reproduce () {} 6 }; 7 8 class Robot {9 public: 10 void speak () {} 11 void sit () {} 12 void oilChange () {13 }; 14 15 template <class T> void perform (T anything) {16 anything. speak (); 17 anything. sit (); 18} 19 20 int main () {21 Dog d; 22 Robot r; 23 perform (d); 24 perform (r); 25 }///:~ The statement in the copy code C ++ is relatively more organized, but it can also achieve the goal of Java: Copy code 1 public interface Performs {2 void speak (); 3 void sit (); 4 }///:~ 5 class extends mingdog extends Dog implements Performs {6 public void speak () {print ("Woof! ");} 7 public void sit () {print (" Sitting ");} 8 public void reproduce () {} 9} 10 class Robot implements Performs {11 public void speak () {print ("Click! ");} 12 public void sit () {print (" Clank! ");} 13 public void oilChange () {} 14} 15 class Communicate {16 public static <T extends Performs> void perform (T extends mer) {17 extends mer. speak (); 18 timer mer. sit (); 19} 20} 21 public class DogsAndRobots {22 public static void main (String [] args) {23 extends mingdog d = new extends mingdog (); 24 Robot r = new Robot (); 25 Communicate. perform (d); 26 Communicate. perform (r); 27} 28} copying code Java code is odd It is strange to use an interface Perform, and then specify <T extends Perform> when defining the generic method in line 16 of the Code (for the declaration method of the generic method, see: [Java Summary 3] Java Generics-first recognized generics), when declaring generics, we did not simply <T> but fixed a boundary, which is equivalent to telling the compiler: the input type must inherit from the Perform interface, so T must have the speak () and sit () methods, so you can call them with confidence. It can be seen that Java's generic usage is cumbersome, and programmers need to consider a lot of things and cannot follow the normal way of thinking. Normally, we think so: I define a method that receives any type, and then call some methods of the input type in this method. Do you have this method, that is what the compiler is going to do. In fact, this interface is also available in python and C ++, but it is implicit. programmers do not need to implement it themselves, and the compiler will automatically handle this situation. Solution 2: Of course, in many cases, we still need to use generics in Java. How can we solve this headache? Show the Class Object of the transfer type: From the analysis above, we can see that in Java generic classes or generic methods, the type information of incoming type parameters is completely lost, it is erased, and we cannot even run a new one in it. At this time, we can solve the problem by using Java's RTTI, that is, the runtime type information (subsequent blog posts), as follows: copy code 1 class Building {} 2 class House extends Building {} 3 public class ClassTypeCapture <T> {4 Class <T> kind; 5 T t; 6 public ClassTypeCapture (Class <T> kind) {7 this. kind = kind; 8} 9 public boolean f (Object arg) {10 return kind. isInstance (arg); 11} 12 public void n EwT () {13 t = kind. newInstance (); 14} 15 public static void main (String [] args) {16 ClassTypeCapture <Building> ctt1 = 17 new ClassTypeCapture <Building> (Building. class); 18 System. out. println (ctt1.f (new Building (); 19 System. out. println (ctt1.f (new House (); 20 ClassTypeCapture <House> ctt2 = 21 new ClassTypeCapture <House> (House. class); 22 System. out. println (ctt2.f (new Building (); 23 System. out. p Rintln (ctt2.f (new House (); 24} 25}/* Output: 26 true 27 false 28 true 29 *///:~ In the previous example, we used instanceof to identify the type failure, because the type information in the generic model has been erased. In code 10th, here we use dynamic isInstance (), and pass in the type label Class <T> so that we only need to use the constructor to pass its Class type information to the generalized Class when declaring the generic Class, in this way, we can compensate for the erasure problem. In the code 13th line, we can also use the factory object Class object to obtain a T-type instance through the newInstance () method. (This can be fully implemented using t = new T (); in C ++, but the type information is lost in Java. I cannot know whether the T type has a non-argument constructor) (In subsequent blog posts about type information in Java such as Class, isInstance (), newInstance (), and so on) solution 3: as mentioned in solution 1, Java uses boundary to solve the problem of Type erasure of generics. We declare an Interface, and then tell the compiler <T extends Interface> when declaring a generalized class or generalized method. The Interface is an Interface that we arbitrarily declare, in this way, we can know which Methods T has and some types of T. 4. When using containers in Java, we often encounter a List-like problem? Extends Fruit> is this declaration a question mark? Is a wildcard. Fruit is a base class of the Fruit type. Its export types include Apple and Orange. Covariant: copy code 1 class Fruit {} 2 class Apple extends Fruit {} 3 class Jonathan extends Apple {} 4 class Orange extends Fruit {} 5 public class CovariantArrays {6 public static void main (String [] args) {7 Fruit [] fruit = new Apple [10]; 8 fruit [0] = new Apple (); // OK 9 fruit [1] = new Jonathan (); // OK 10 // Runtime type is Apple [], not Fruit [] or Orange []: 11 try {12 // Compiler allows you to add Fru It: 13 fruit [0] = new Fruit (); // ArrayStoreException 14} catch (Exception e) {System. out. println (e);} 15 try {16 // Compiler allows you to add Oranges: 17 fruit [0] = new Orange (); // ArrayStoreException 18} catch (Exception e) {System. out. println (e);} 19} 20}/* Output: 21 java. lang. arrayStoreException: Fruit 22 java. lang. arrayStoreException: Orange 23 *///:~ Copy the code. First, let's take a look at the covariant in the array (the covariant means that the child type can be used as the base type). Java arrays support covariant. As shown in the above Code, we will find that the declared Apple array is stored with Fruit reference, but when we add elements to it, we can only add Apple objects and their child types, if you try to add another Fruit sub-type such as Orange, an error will be reported in the compiler. This is very reasonable. An Apple-type array obviously cannot be put in Orange; however, in line 13 of the code, we will find that if we want to put the Fruit base type object, the compiler will allow it, because our array reference is of the Fruit type, however, at runtime, the compiler will find that the Fruit reference actually processes an Apple array, which will throw an exception. However, we translate the array operation to List, as shown below: Copy code 1 public class GenericsAndCovariance {2 public static void main (String [] args) {3 // Wildcards allow covariance: 4 List <? Extends Fruit> flist = new ArrayList <Apple> (); 5 // Compile Error: can't add any type of object: 6 // flist. add (new Apple (); 7 // flist. add (new Fruit (); 8 // flist. add (new Object (); 9 flist. add (null); // Legal but uninteresting 10 // We know that it returns at least Fruit: 11 Fruit f = flist. get (0); 12} 13 }///:~ We use wildcards to copy the code. <? Extends Fruit>, which can be understood as a list of any types inherited from Fruit. We will find that not only the Orange object is not allowed to be put into the List, but even Apple is not allowed to put it in this List. This shows that a problem List cannot have covariance like an array. Why is this happening here? By checking the source code of ArrayList, we can find that when we declare ArrayList <? The add () parameter in extends Fruit> is changed "? Extends Fruit ", at this time the compiler does not know which specific child type you want to add to Fruit, then it will not accept any type of Fruit. But here we find that we can normally get () an element, which is well understood, because the type parameter we declare is <? Extends Fruit>, the compiler can safely return elements. It should be returned if I know that the content in the List must be a Fruit. Inverter: We found that the get method is acceptable. What should we do when we want to use the set or add method? You can use an inverter, that is, an ultra-type wildcard. Copy code 1 public class SuperTypeWildcards {2 static void writeTo (List <? Super Apple> apples) {3 apples. add (new Apple (); 4 apples. add (new Jonathan (); 5 // apples. add (new Fruit (); // Error 6} 7 }///:~ Copy the code here <? Super Apple> This List stores some basic types of Apple, so it is safe to put Apple or its Subtypes into this List. Summary: <? Super T> If the inverter specifies that the generic class holds the T base class, then T can definitely be placed in <? Extends T> indicates that the generic class holds the T export class, and the returned value must be the T covariant type, summary of a bunch of also found that Java generics are really scum, not easy to use, the requirements for programmers will be higher, accidentally will make mistakes. This is why we often see various warnings when using generalized classes in class libraries...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.