These two days nothing to learn under the reflection. By reflecting we can modify the values of the fields in the object.
As the following code
Grade grade=New Grade (); Field F=grade. class. Getdeclaredfield ("name"); F.setaccessible (true); " Third Grade One Class ");
It was so easy, and I thought about how the list Type field would be modified by reflection.
So I tried, and finally made it out.
Prepare two classes first.
Public classGrade {PrivateString name; PrivateList<student>students; PublicGrade () {} PublicGrade (String name,list<student>students) { This. name=name; This. students=students; } PublicString toString () {StringBuilder sb=NewStringBuilder (); for(Student s:students) {sb.append (S.getnumberid ()+" "); } returnsb.tostring (); }}
Public class Student { private String name; Private int Age ; Private String Numberid; Public String Getnumberid () { return numberid; }}
The code implemented below
Public classProgram { Public Static voidMain (string[] args)throwsnosuchfieldexception, SecurityException, IllegalArgumentException, Illegalaccessexception, instantiationexception{Grade Grade=NewGrade (); Field F=grade.class. Getdeclaredfield ("name"); F.setaccessible (true); F.set (Grade,"Third Grade One class"); Field field=grade.class. Getdeclaredfield ("Students"); if(List.class. IsAssignableFrom (Field.gettype ())) {List arraylist=NewArrayList (); Type type=Field.getgenerictype (); //This determines whether type is a parameterized type. such as collection<string> is a parameterized type. if(TypeinstanceofParameterizedtype) { //gets the type parameter type of the type. You can check out the JDK Help documentation for Parameterizedtype's explanation. Class clazz= (Class) ((Parameterizedtype) type). Getactualtypearguments () [0]; Object obj=clazz.newinstance (); Field FF=clazz.getdeclaredfield ("Numberid"); Ff.setaccessible (true); Ff.set (obj,"1001010"); Arraylist.add (obj); } field.setaccessible (true); Field.set (grade, ArrayList); } System.out.println (grade); }}
This is a simple demo to share with you.
Java uses reflection to modify the values in the list Type field in the object.