Generics implement the concept of parameterized types , so that code can be applied to multiple types, releasing constraints between a class or method and the type used. Generics were introduced at the beginning of JDK 1.5, but the way Java implemented generics differed greatly from C + + or C #. When it comes to generic writing, it seems as if everything is taken for granted. But in fact, Java generics still have a lot of tricky things, the compiler in the back for us to do many things. Let's take a look at some of the easy-to-ignore points of Java generics.
Generics do not support covariant
What is co-change? Let me give you an example.
new Apple[10// OK
A subclass array can be assigned a reference to an array of parent classes. Generics, however, do not support this covariance.
new// 无法通过编译
But we can use wildcard characters to solve
new ArrayList<Apple>();// 使用通配符解决协变问题
Wildcard Upper bound wildcard character
List<? extends fruit> flist = arrays.aslist (new Apple ()); Apple a = (apple) flist.get (0 ); //No warning flist.contains (new Apple ()); //Argument is ' Object ' flist.indexof (new Apple ()); //Argument is ' Object ' //flist.add (New Apple ()); Unable to compile
List<? extends Fruit>A List that represents a particular type (Fruit or its subclasses), but the compiler does not care (not to know) what the actual concrete type is. It is important to note that this does not mean that the list can hold any type of fruit!
Because the specific type of the list is not deterministic, and the Java generics do not support covariant, methods with generic type parameters cannot be called normally. For example add(T item); , even a pass object cannot be compiled.
But for a method that returns a type that is generic, for example T get(int index); , the return value type is the same as the upper bound type. As the previous example code calls, the flist.get(0) return value is the fruit type.
Nether Wildcard Characters
staticvoidsuper Apple> list) {// list.add(new Fruit()); // 无法编译 Object object = list.get(0);// pass }
In the Code
List<? super Apple> listIndicates that the type that list holds is Apple's parent class type, but similar to the upper bound wildcard, which does not mean that the list can hold an object of any of Apple's subclass types, and that the compiler does not know what the list's specific type is. Therefore, list.add(new Fruit()); it cannot be compiled.
Unbounded wildcard characters
List<?> listIndicates that a list particular type of List is held, but not exactly what type it is. Instead of passing in a List list generic parameter, it means that the type of element the list holds is Object .
is all generic information erased?
The so-called Erasure is simply the erasure of the bytecode in the method's Code property (that is, the logic within the method), and the fact that the metadata (the declaration of classes and interfaces, the declaration of a class field) retains the generic information.
The big words of reference R are:
On the side of the statement, the source of what is written to the runtime can see what;
On the use of one side, the source of what is written to the run time is gone.
public class genericclass <t > { //1 Private list<t> List; //2 private Map<string, t> map; //3 public <U> U genericmethod (map<t, u> m) {//4 list<string> List = new Array List<> (); //5 return null ; }}
In the above code, notes 1 to 4 of T and U are kept in the class file, what the source code is, then what is obtained through reflection. That is, at run time, it is impossible to get to the exact type of T and U.
But at run time, the generic information for local variables inside the method is completely erased. The specific type of list in note 5 above is not available at run time.
Are you sure you can't get to a generic type?
The interviewer at the time today asked me this question, and I had a shallow understanding of generics that the compiler would erase all of the generic information, and the runtime would be incompetent to get to a specific generic type. In fact, this is not the case, as described above, after JDK1.5, the format of the class has changed, the compiler will declare the class, interface, method of the generic information to the bytecode. So through reflection, this information can still be obtained. However, to get to a specific generic type, you can generally get only the generic type that is used to inherit from the parent class.
Like what:
publicclass SubClass extends Base<String> { }
Then base-bound generic types can be obtained. The Subclass.class call getGenericSuperclass can get the type to which T is bound.
Type type = SubClass.class.getGenericSuperclass(); Type targ = ((ParameterizedType) type).getActualTypeArguments()[0]; // SubClass<java.lang.String> // class java.lang.String
The specific usage can refer to the source code of Gson and Guice:
-
https://github.com/google/guice/blob/abc78c361d9018da211690b673accb580a52abf2/core/src/com/google/inject/ Typeliteral.java#l94
-
Https://github.com/google/gson/blob/master/gson/src/main/java/com/google/gson/internal/%24Gson%24Types.java
Bridge method
To make the bytecode generated by the Java generic method compatible with the bytecode of the previous 1.5, the method generated by the compile-time itself. As the name implies, the bridge method is a bridge that communicates generics and polymorphism.
The
can use the Method.isbridge () method to determine whether a method is a bridging method, in which the bridging method is marked as Acc_bridge and acc_ Synthetic .
publicclass Fruit<T> { T value; publicgetValue() { return value; }}publicclass Apple extends Fruit<String> { @Override publicgetValue() { return"foo was call"; }}
The bytecode generated by the anti-compilation:
Public class Apple extends Fruit<java. Lang. String> { PublicApple (); Code:0: Aload_01: invokespecial#1//Method Fruit. " <init> ":() V 4:return PublicJava.lang.String GetValue (); Code:0: LDC#2//String calling 2: Areturn PublicJava.lang.Object GetValue (); Code:0: Aload_01: invokevirtual#3//Method GetValue: () ljava/lang/string; 4: Areturn}
The compiler automatically generated a bridge method for us, the bridge method returns the type object, and internally invokes another GetValue method that we have customized.
In Java code, the signature of a method includes only the method name, the parameter order, and the parameter type, while the signature in the bytecode also includes the method return value and the checked exception table. Therefore, the bridge public Object getValue() method public String getValue() can coexist in the same class file as the JVM.
Because of the compile-time generic erase mechanism, methods with generic parameters in the parent class are replaced with the object type. To have subclasses rewrite the parent class with generic parameters, the method of the parent class needs to be directly replicated through the bridge method, and then the bridge method calls the subclass custom method, as an example, the subclass Apple Bridge method public Object getValue() directly overrides the parent class fruit public Object getValue() , Then the bridge method internally calls the subclass Apple public String getValue() . Therefore, Java uses the bridge method to ensure that the polymorphic mechanism is not destroyed by the implementation of generics.
Reference
- 1190000005337789
- http://rednaxelafx.iteye.com/blog/586212
- http://blog.csdn.net/mhmyqn/article/details/47342577#
- http://blog.csdn.net/lonelyroamer/article/details/7868820
Do you really understand Java generics?