First, let's look at how generic classes work, and what's the benefit of using generic classes.
Import Java.lang.reflect.Method;
Import Java.lang.reflect.ParameterizedType;
Import Java.lang.reflect.Type;
Import Java.util.Date;
Import Java.util.HashMap;
Import Java.util.Map;
Import Java.util.Set;
Import Java.util.Vector;
public class Google {
public static void Main (string[] args) throws exception{
Generics are to be seen by the compiler and can be assigned other types of values with reflection through a generic
Hashmap<string, integer> maps = new hashmap<string, integer> ();
Maps.put ("sad", 123);
Maps.put ("SAASDD", 12323);
Illegally adding other type characters to maps by reflection
Maps.getclass (). GetMethod ("put", Object.class,object.class). Invoke (Maps, "Reflection is strong", "success". ");
Traversing the values of the Maps collection
Using custom generic classes to add the original
set<map.entry<string,integer>> EntrySet = Maps.entryset ();
for (map.entry<string,integer> M:entryset) {
System.out.println (M.getkey () + ":" + m.getvalue ());
}
Calling generic generics
Printhashmap (maps);
ClassLoader.class.getClassLoader (). GetClass ();
Custom class Loader
Class is loaded, it is first given to the previous level, which is loaded from the parent
Vector<date> v = new vector<date> ();
/**
What about us? Get the type of the generic parameter, where we can put generics into a method
* Java provides us with the parameter types of the generic type in the method
*/
Method Applymethod = Google.class.getMethod ("Applytype", Vector.class);
type[] types = Applymethod.getgenericparametertypes ();
Parameterizedtype ptype = (parameterizedtype) types[0];
System.out.println (Ptype.getrawtype ());
System.out.println (ptype.getactualtypearguments () [0]);
}
//(?) A question mark indicates any parameter type, which is a wildcard character
//? Extends number up qualifier, cannot exceed the type of number inclusion
//? Super. First down qualifier
public static void Applytype (vector<date> value) {
}
public static void Printhashmap (HASHMAP<?,? extends Number> maps) {
Cannot add element operation here
System.out.println (Maps.size ());
}
public static <T> void Printhashmaps (hashmap<t,t> maps,t key,t value) {
Maps.put (key, value);
System.out.println (Maps.size ());
}
The template method design pattern parent class defines the process details of the class implementation (this method can only be applied in C + +, more than Java Virtual machine relationships, not implemented here)
This template is very useful
public static <T> t Add (t x,t y) {
return null;
}
}
Here we customize a simple generic class
//Custom generic class generic class
public class Tobe<t> {
public void Add () {
& nbsp;
}
public T find (int i) {
& nbsp return null;
}
//Static methods are not constrained in generic classes
public static <E> e Add (E x) {
& nbsp; return null;
}
//To get the actual type of the parameters inside the generic by reflection
public void del (T i) {
& nbsp;
}
}