Don't hold on to the past and reject new ideas and challenges.
The content of this lecture: Generics and reflection mechanism
I. basic concepts of generics
Generics are a new feature of Java SE 1.5, and the nature of generics is a parameterized type, meaning that the data type being manipulated is specified as a parameter. This type of parameter can be used in the creation of classes, interfaces, and methods, called generic classes, generic interfaces, and generic methods, respectively.
For example,:arraylist<student> stu=new arraylist<student> (), the type is determined by generics, no more strong turn.
There are several advantages to using generics:
1. Type safety
2. Backwards compatibility
3. Clear level
4, the performance is high, has the GJ (generics Java) written code can provide the Java compiler and the virtual machine to bring more type information, this information to the Java program to do further optimization provides the condition.
Second, reflection mechanism
The reflection mechanism is the mechanism by which all methods and members of a generic fixed class can be displayed so that programmers can determine whether the program is written incorrectly.
Let's take a look at two examples
Package A;public class Text {public static void main (string[] args) {animal<string> a=new animal<string> ("Dan "); A.showtypename ();}} Define a class Animal<t> {private T o;public Animal (t o) {this.o=o;} public void Showtypename () {System.out.println ("type is:" +o.getclass (). GetName ());}}
Type is: java.lang.String
Package A;import Java.lang.reflect.method;public class Text {public static void main (string[] args) {animal<bird> a =new animal<bird> (New Bird ()); A.showtypename ();}} Class bird{public void Sleep () {System.out.println ("Sleep");} public void Eat () {System.out.println ("eat");}} Define a class Animal<t> {private T o;public Animal (t o) {this.o=o;} Get the type name of T public void Showtypename () {System.out.println ("type is:" +o.getclass (). GetName ());//through the reflection mechanism, We can get a lot of information about this type of T method[] M=o.getclass (). Getdeclaredmethods (); for (int i=0;i<m.length;i++) {System.out.println (M [I].getname ());}}}
The type is: A. Birdsleepeat
This is where we go, take your time and enjoy it
Study Note 18: Generics