java-generics (Generic) in-depth use (combined with reflection)

Source: Internet
Author: User
Tags class definition uppercase letter

Generics are provided to the Javac compiler to limit the input types in the collection, let the compiler block illegal input in the source program, the compiler compiles a collection of type descriptions to remove "type" information , so that the efficiency of the program is not affected, For parameterized generic types, the return value of the GetClass () method is exactly the same as the original type. Because the compiled bytecode removes generic type information, as long as you can skip the compiler, you can add other types of data to a generic collection, for example, by using reflection to get the collection, and then calling its Add method.

Summary: generics are only valid at the time of the compiler, are not valid at run time, and the "type" information that it indicates during runtime is removed as:

1. Generics (reference type only) using rules

The following terms are involved in the ArrayList class definition and the ArrayList class reference: The whole is called the ArrayList generic type

E in ArrayList is called a type variable or type parameter the entire ArrayList is called a parameterized type

An integer in ArrayList is called an instance of a type parameter or an actual type parameter

ArrayList in the <> read typeof

ArrayList called primitive types

The compatibility of the parameterized type with the original type:

Parameterized types can reference an object of the original type, compile a report warning,

For example, collection<string> C = new Vector ();//Can

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

Collection C = new Vecto<string>r ();//Yes.

The third case:

Vector v1=new vector<string> ();//conforms to the top case

Vector<object> V=v1; can also, in accordance with the second case of the above

Parameterized types do not consider inheritance relationships for type parameters:

Vector<string> v = new vector<object> ();//Error

Vector<object> v=new vector<string> ();//Error

2. What is the generic type? Wildcard characters

Problem: Define a method that prints out all the data in a collection of arbitrarily parameterized types, how is this method defined?

Error mode:

       Public Static void printcollection (collectioncols) {              for(Object obj:cols) {System.out.println (obj);}               /* cols.add ("string");//Yes cols = new HashSet ();//will report an error! */

The right way:

 Public Static void printcollection (collection<?> cols) {                     for(Object obj:cols) { System.out.println (obj); }                 //Cols.add ("string"); // error, because it does not know its future match is bound to    be a string                cols.size (); // Yes, this method has no relation      to the type parameter new hashset<date> ();}                     

Summary: Wildcard characters can be used to refer to various other parameterized types ,? The variable defined by the wildcard is used primarily as a reference, and can be called a method that is not related to parameterization.

You cannot invoke a method that is related to a parameterized type .

3. What is the generic type? Expansion of wildcard characters

To qualify the upper bounds of a wildcard:

Correct: vector x = new vector ();

Error: Vector x = new vector ();

To limit the bottom bounds of a wildcard:

Correct: vector x = new vector ();

Error: Vector x = new vector ();

<?> and <E>

Class<?> c=new class<e> ();//correct

Class<e> c=new class<?> ();//error, ie? Can "=" any parameter, but a specific parameterized type "="? Error.

Summary: Qualifying wildcards always include yourself. can only be used as a reference and cannot be used to assign values to other variables

Vector y = new vector (); Vector x = y;

The above code is wrong, and the principle is the vectorx11 = new Vector ();

You can only assign a value by forcing the type conversion mode.

4. Methods for defining generics

    • A generic type (or generic) in Java is similar to a template in C + +. But this similarity is limited to the surface, and generics in the Java language are basically implemented in the compiler.
    • Used by the compiler to perform type checking and type inference, and then generate generic non-generic bytecode, an implementation technique known as erase (erasure)
    • Java's generic methods are not as powerful as C + + template functions, and the following code in Java cannot be compiled: <T> t Add (t x,t y) {return (T) (x+y);
    • return null; The angle brackets for the type parameter that is used to place the generic should appear after all other modifiers of the method and before the return type of the method, that is,
    • Immediately before the return value. By convention, type parameters are usually represented in a single uppercase letter.
    • In addition to using the extends qualifier when you apply generics, you can also use the extends qualifier when defining generics, such as the definition of the Class.getannotation () method.
    • And you can use & to specify multiple boundaries, such as <v extends Serializable & cloneable> void Method () {}
    1. only reference types can be the actual parameters of a generic method , swap (new int[3],3,5), and statements report compilation errors.
    2. Generics can be used in common methods, construction methods, and static methods.
    3. You can also use a type variable to represent an exception, called a parameterized exception, that can be used in the throws list of methods, but not in a catch clause.

You can have more than one type parameter in a generic, with a comma in the angle brackets in which they are defined,

For example: public static <K,V> V GetValue (K key) {return map.get (key);}

//<T> must declare that this is for you to use "T" parsing, <t extends u&v> can also, <t Super u> can not       Public<T>t method1 (t x,t y) {returny; }          Public<textendsNumber>voidmethod2 (T x) {}//multiple parameters of T    Public Static<K,V>v GetValue (K key) {v map=NULL; return(V) ((arraylist<integer>) map). Get (int) key); }       //how exceptions Take generics     Private Static<textendsException>voidSayHello ()throwsT {Try{                        }Catch(Exception e) {Throw(T) e; }           }

5. Defining classes for Generics

 public  class  genericdao<e>< Span style= "color: #000000;" > { //  class E used by multiple methods, declared above the class <E>  public   add (e e) {}  //  static The <e> method uses an E that must be declared on its own method, and cannot use the <E>  static  <E> void   method (e e) {  public  void   update (e-e) {}}  

Note: When you parameterize a generic type, the instance of the type parameter must be a reference type and cannot be a base type. When a variable is declared as generic,

Can only be called by instance variables, methods, and inner classes, not by static variables and static methods . Because a static member is a class that is parameterized by all

Shared, so static members should not have class-level type parameters

6.Type (interface)

Type is the public advanced interface for all types in the Java programming language. They include primitive types, parameterized types, array types, type variables, and base types.

Java.lang.reflect Interface Type
All known sub-interfaces:
Genericarraytype, Parameterizedtype, Typevariable<d>, Wildcardtype
All known implementation classes:
Class

7. Reflection, advanced application of generics

 Public classGenerictest { Public Static voidMain (string[] args)throwsException {//How to get a specific generic type declared on a method//such as: public void Applyvector (Vector<date> v); How to know that the Vector is Date, that is, how to get the generic type in <T>//workaround: Get the generic type on the method using the Getgenericparametertypes () in the reflected methods classMethod Applymethod=generictest.class. GetMethod ("Applyvector", Vector.class, Set.class); Type [] TP=applymethod.getgenericparametertypes (); System.out.println (tp[0]); Parameterizedtype P= (Parameterizedtype) tp[1]; System.out.println (P.getactualtypearguments () [0]); }        Public voidApplyvector (vector<date> v,sets) {}}

java-generics (Generic) in-depth use (combined with reflection)

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.