/** * * @authorAdministrator * Function: The necessity of generics (parameterized type) (safe and simple)*/ Packagecom.test;ImportJava.util.*; Public classTest {/** * @paramargs*/ Public Static voidMain (string[] args) {//TODO auto-generated Method Stub//ArrayList al = new ArrayList ();// //Create a dog//Dog dog1 = new Dog ();// //put into the collection//Al.add (DOG1); //the sentence will be error-ArrayList return the object type must be strong or use generics//Dog temp2 = al.get (0);// //removed// //forcing a type conversion requires the developer to be able to predict the actual parameter type, the compiler does not prompt the error//There are security implications// //Dog temp = (dog) al.get (0);// // //compiler does not report errors, there are security risks, the type conversion exception// //Cat temp = (cat) al.get (0); //the benefit of generics is that the security of types is checked at compile-time//using generics does not errorArraylist<dog> Al =NewArraylist<dog>(); Dog Temp= Al.get (0); }}classcat{PrivateString color; Private intAge ; PublicString GetColor () {returncolor; } Public voidsetcolor (String color) { This. color =color; } Public intGetage () {returnAge ; } Public voidSetage (intAge ) { This. Age =Age ; } }classdog{PrivateString name; Private intAge ; PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } Public intGetage () {returnAge ; } Public voidSetage (intAge ) { This. Age =Age ; } }
Java Generic reflection mechanism (i)