A simple use of reflection in Java

Source: Internet
Author: User

In other places before the technical articles re-organized, convenient for their own memories, but also for others to learn from.

When I was working, I sent this code:

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); The public static void Test (list list) is throws Exception, illegalaccessexception {for (int i = 0; i < List.siz E ();            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].se                Taccessible (TRUE);            } System.out.println (Fields[j].get (OI)); }        }    }}

This code only uses the Getdeclaredfields () method in the reflection in Java to get all the declared objects in the object (both public and private).
In addition, the Isaccessible () method can return the value of the accessible flag that returns the reflected object. That is, whether this property can be accessed by another object (that is, it is not a public attribute).
Setaccessible (Boolean flag) can set an accessible flag for a reflected object and set it to true to change the access adornment of the property to public.

A simple use of reflection in Java

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.