One of the new features added by jdk1.5 is the generic type. Comments on generics are mixed. If you don't talk much about it, Let's first look at his principles.
Generics are provided for the javac compiler. They can limit the input type in the set and allow the compiler to intercept illegal input in the source program. When the compiler compiles a set with type descriptions, the type information is removed, for parameterized generic types, the return value of the getclass () method is exactly the same as that of the original type.
For the following source program:
public class Oliver {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("str1");
list.add("str2");
String str = list.get(0);
}
}
Decompiled content after being compiled into Oliver. class:
public class Oliver {
public Oliver() {
}
public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add("str1");
list.add("str2");
String str = (String) list.get(0);
}
}
That is to say, Java's generic model only imposes parameter restrictions on the compiler. In fact, there is no Optimization on the performance!
The bytecode generated by compilation removes generic type information. As long as the compiler can be skipped, other types of data can be added to a generic set.
The following code skips the compiler check using the reflection mechanism:
public class Oliver {
public static void main(String[] args) throws Exception {
ArrayList<Integer> list = new ArrayList<Integer>();
list.getClass().getMethod("add", Object.class).invoke(list, "ssss");
System.out.println("list:" + list.get(0));
}
}
Output result:
List: ssss
For Java generics, Bruce Ecke (author of thinking in Java) once gave such a comment:
Guess what. I really don't care. you want to call it "generics," Fine, implement something that looks like C ++ Or Ada, that actually produces a latent typing mechanic like they do. but don't implement something whose sole purpose is to solve the casting problem in containers, and then insist that on calling it "generics. "Of course, Java has long precedence in arrogantly mangling well-accepted meanings for things: one that participates ularly stuck in my craw was the use of" Design Pattern "to describe getters and setters. in JDK 1.4 we were told some lame way to use assertions which was a backward justification for them being disabled by default. JDK 1.4 also had to invent its own inferior logging system rather than using the openly created, well-tested and well-liked log4j. and we 've also been told always times about how Java has been as fast or faster than C ++, or about how one or another feature is great and flawless. I point to the threads implementation which has had major changes quietly made from version to version with not so much as a peep of apology or admission that "hey, we really screwed up here. "or maybe I was just not on that participant announcement list.