A simple use of reflection in Java and a simple use of Java reflection

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.