A simple use of reflection in Java and a simple use of Java reflection
Repeat the previous technical articles in other places to help you remember and learn from others.
I sent such a piece of code at work:
package cn.com.hanbinit.test; import java.lang.reflect.Field;import java.util.ArrayList;import java.util.List; public class Test { public static void main(String[] args) throws IllegalArgumentException, Exception { Person p1 = new Person("111", "aaa"); Person p2 = new Person("222", "bbb"); List list = new ArrayList(); list.add(p1); list.add(p2); test(list); } public static void test(List list) throws Exception, IllegalAccessException { for (int i = 0; i < list.size(); i++) { Field[] fields = list.get(i).getClass().getDeclaredFields(); Object oi = list.get(i); for (int j = 0; j < fields.length; j++) { if(!fields[j].isAccessible()){ fields[j].setAccessible(true); } System.out.println(fields[j].get(oi)); } } }}
This Code uses the getDeclaredFields () method in Java reflection to obtain all declared objects (including public and private) in the object ).
In addition, the isAccessible () method can return the value of the accessible flag of the reflected object, that is, whether this attribute can be accessed by other objects (that is, whether it is a public attribute ).
SetAccessible (boolean flag) can set an accessible flag for the reflection object. Setting it to true is equivalent to modifying the attribute access to public.