My java Study Notes (13) Reflection (part 2), study notes
Whining... This evening is a bit of a thing... As a result, there was no eclipse in the lab, and the command line was used. As a result, the environment variables were not properly configured for a long time .. Now .. Ah ..
1. The key method for viewing object fields is the get method in the Field class.
Field f = c1.getDeclareFields ("name"); Object value = f. get (obj); // value is the current value of the name Field in obj.
2. The default behavior of the reflection mechanism is limited by java access control.
3. If a java program is not controlled by the security manager, it can overwrite access control.
4. The setAccessible methods of the Field, Method, and Constructor objects can bypass the security management access.
f.setAcceessible(true);
5. The setAccessible Method is a Method in the AccessibleObject class. It is a public superclass of the Field, Method, and Constructor classes.
6. You can also set the value of the f field of the obj object through the set method.
f.set(obj,value);
Related instance code
Test class
import java.util.ArrayList;public class Testee{public static void main(String[] args){ArrayList<Integer> s = new ArrayList<>();for(int i = 1; i <=5 ; i++){s.add(i*i);}System.out.println(new ObjectAnalyzer().toString(s));}}
Function
import java.lang.reflect.*;import java.util.*;public class ObjectAnalyzer{private ArrayList<Object> v = new ArrayList<>();public String toString(Object obj){if(obj == null)return "null";if(v.contains(obj))return "...";v.add(obj);Class c1 = obj.getClass();if(c1 == String.class)return (String)obj;if(c1.isArray()){String r = c1.getComponentType() + "[]{";for(int i = 0; i < Array.getLength(obj);i++){if(i > 0)r +=",";Object val = Array.get(obj,i);if(c1.getComponentType().isPrimitive())r += val;elser += toString(val);}return r + "}";}String r = c1.getName();do{r += "[";Field[] fields = c1.getDeclaredFields();AccessibleObject.setAccessible(fields,true);for(Field f:fields){if(!Modifier.isStatic(f.getModifiers())){if(!r.endsWith("["))r += ",";r += f.getName() + "=";try{Class t = f.getType();Object val = f.get(obj);if(t.isPrimitive())r += val;elser += toString(val);}catch(Exception e){e.printStackTrace();}}}r += "]";c1 = c1.getSuperclass();}while(c1 != null);return r;}}
Print results
Ah .. It looks good without the eclipse console ..