Generic and bridge methods, generic
In Java generics, there is a method called type erasure. That is to say, generics are effectively and securely used for type verification during compilation. However, during runtime, this generic type will be replaced by the top-level parent class (if there is no inheritance relationship, it will be replaced by an Object), and then the type will be converted to the target type, this type of erasure also exists in generic methods, but method erasure brings two complicated problems.
public class ParentString<String> { String src; public void setSrc(String src){ this.src=src; }}
public class ChildString extends ParentString<String> { String s="childString"; public void setSrc(String src){ src=s; }}
After the type erasure, the Code evolves as follows:
public class ChildString extends ParentString { String s="childString"; public void setSrc(String src){ src=s; }}
However, it is strange that another setSrc method inherited from ParentString is caused by type erasure, that is, setSrc (Object String ).
Because the parameter types are different, there are two different methods, but this should not happen. Consider the statement sequence below explain
ChildString childString=new ChildString(); ParentString<String> parentString=childString; parentString.setSrc("aaa");
In general, the relationship is through polymorphism. parentString references the ChildString method of the subclass. The problem is that the type erasure conflicts with polymorphism. To solve this problem, you need to generate a bridge method in ChildString)
public void setSrc(Object src){ setSrc((String)src); }
It is worth noting that the bridge method is not only used for generic types, but also for synthesis to maintain polymorphism. When a method overwrites another method, you can specify a more strict return type.
There is another knowledge point to supplement
Reprinted please explain the original source: http://www.cnblogs.com/xxzhuang/p/5968331.html Thank you for your cooperation.