Determine type security during compilation-generic)

Source: Internet
Author: User

Generics are provided to the javac compiler. You can restrict the input types in the set so that the compiler blocks the originalProgramWhen the compiler compiles a set with the type description, the "type" information is removed, so that the program running efficiency is not affected. For parameterized generic types, getclass () the Return Value of the method is exactly the same as that of the original type. Because the bytecode generated by compilation removes the generic type information, as long as the compiler can be skipped, you can add other types of data to a generic set. For example, you can use reflection to obtain the set and then call the add method.

Arraylist <E> class definition and arraylist <integer> class reference involve the following terms:

The whole is called arraylist <E>Generic Type, E in arraylist <E> is calledType Variable or type parameter, The entire arraylist <integer> is calledParameterized typeThe integer in arraylist <integer> is calledType parameter instance or actual type parameterIn arraylist <integer>, <> refers to typeof. arraylist is called the original type.

Compatibility between parameterized types and original types:
A parameterized type can reference an object of the original type and compile a report warning, for example,

 
Collection <string> C =NewVector ();

The original type can reference an object of the parameterized type and compile the report warning, for example,

Collection c =NewVector <string> ();

Parameterized types do not consider the inheritance relationship of type parameters:

 
Vector <string> V =NewVector <Object> ()//ErrorVector <Object> V =NewVector <string> ()//Also incorrect
Type Erasure

The primary prerequisite for a correct understanding of the generic concept is to understand the type erasure ). The generics in Java are similar to the templates in C ++, but the similarity is limited to the surface. The generics in Java are basically implemented at the compiler level. It is a type check and type diagnosis performed by the compiler, and then a common non-generic bytecode is generated, that is, in the generated JAVA byteCodeDoes not contain the type information in the generic type. When using the generic type, the type parameter is removed by the compiler during compilation. This implementation technology is called type erasure. For example, the List <Object> and list <string> types defined in the Code will be changed to list after compilation. What JVM sees is only list, and the type information appended by generics is invisible to JVM. The Java compiler tries its best to discover possible errors during compilation, but it still cannot avoid type conversion exceptions at runtime.

Many of the strange features of generics are related to the existence of this type of erasure, including:

    • Generic classes do not have their own class objects. For example, there is no list <string>. Class or list <integer>. class, but only list. Class;
    • Static variables are shared by all instances of the generic class. For Classes declared as myclass <t>, the method for accessing the static variables in the class is still myclass. mystaticvar. Objects Created through new myclass <string> or new myclass <integer> share a static variable.
    • Generic Type parameters cannot be used in catch statements for Java exception handling. Because exception handling is performed by JVM at runtime. Because the type information is erased, JVM cannot distinguish two exception types: myexception <string> and myexception <integer>. For JVM, they are all of the myexception type. The catch statement corresponding to the exception cannot be executed.
Instance analysis

After learning about the type erasure mechanism, you will understand that the compiler undertakes all the type checks. The compiler prohibits certain generic usage to ensure the security of the type. The list <Object> and list <string> mentioned above are analyzed as follows:

  Public   void  inspect (list   List) {  for   (Object OBJ: List) {system. out. println (OBJ);} List. add ( 1); ///   this operation is valid in the context of the current method.  }  Public   void   test () {list  
   
     STRs = 
     New  arraylist 
     
      (); inspect (STRs);  
     ///  
      compilation error }
    
   

In this Code, the inspect () method accepts list <Object> as the parameter. When the test method tries to pass in list <string>, a compilation error occurs. If this method is allowed, you can add a number to the set through list. Add (1) in the inspect method. In this way, in the test method, an integer type object is added to the set declared as list <string>. This apparently violates the type security principle and will certainly throw classcastexception at some time. Therefore, the compiler prohibits such behavior. The compiler checks possible type security issues as much as possible. If it is determined that this is in violation of relevant principles, a compilation error will be given. When the compiler cannot determine whether the type is used correctly, a warning is given.

Wildcard and Upper/Lower Bounds

When using generic classes, you can specify a specific type. For example, if list <string> is used, the specific type is declared as string. Can you also use wildcards? To represent unknown types, such as list <?> It is declared that the element types contained in the list are unknown. Wildcards represent a group of types, but the specific types are unknown. List <?> All declared types are acceptable. But list <?> It is not equivalent to list <Object>. List <Object> actually determines that the list contains the object and its subclass. You can reference the object when using it. And list <?> The element types contained in the table are uncertain. It may contain string or integer. If it contains a string, it is wrong to add an integer element to it. Because the type is unknown, you cannot use the new arraylist <?> () Method to create a new arraylist object. Because the compiler cannot know the specific type. But for list <?> Elements in can always be referenced by objects, because although the type is unknown, it must be an object and its subclass. Consider the following code:

Public VoidWildcard (list <?>List) {list. Add (1 );//Compilation Error}

As shown above, a compilation error always occurs when you try to operate a wildcard class. The reason is that the type indicated by the wildcard is unknown.

Because list <?> The elements in can only be referenced by objects, which is not very convenient in some cases. In these cases, the upper and lower bounds can be used to limit the range of unknown types. Such as list <? Extends number> indicates that the element type in the list may be number and its subclass. And list <? Super number> indicates that the list contains the number and its parent class. After the upper bound is introduced, you can use the method defined in the upper bound class when using the type. For example, access list <? Extends number>, you can use methods such as intvalue of the number class.

Develop your own generic classes

Generic classes are basically the same as general Java classes, but the type parameters declared by <> are added to the class and interface definitions. A class can have multiple type parameters, such as myclass <x, y, z>. You can specify an upper bound when declaring each type parameter. The declared type parameters can be used as method parameters and return values, or as the types of domain and local variables, just as common types in the Java class. However, due to the type erasure mechanism, type parameters cannot be used to create objects or as static variables. Consider the correct and incorrect usage in the following generic classes.

     Class Classtest <XExtends Number, y, z> {  Private  X;  Private   Static Y; //  Compilation error. It cannot be used in static variables.          Public  X getfirst (){              Return  X ;}  Public   Void  Wrong () {z = New Z (); //  Compilation error. You cannot create an object.  }} 

 

References:

Http://www.infoq.com/cn/articles/cf-java-generics

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.