In-depth exploration of the Java reflection mechanism (fields)

Source: Internet
Author: User

Through java. Lang. Reflect. field, we can use member variables of the runtime class.

Obtaining field objects, field names and Field Types

package tao.xiao.action;import java.lang.reflect.Field;public class A implements IT1 {private int a;protected String b;public float c;public double[] d;public static void main(String[] args) throws ClassNotFoundException {Class myClass = Class.forName("tao.xiao.action.A");Field[] fields = myClass.getFields();for (Field field : fields)System.out.println(field);}}

The running result is:

public float tao.xiao.action.A.cpublic double[] tao.xiao.action.A.d

Visible, only accessiblePublicMember

If you know the name of a member, you can directly access it by name.

package tao.xiao.action;import java.lang.reflect.Field;public class A implements IT1 {private int a;protected String b;public float c;public double[] d;public static void main(String[] args) throws ClassNotFoundException, SecurityException, NoSuchFieldException {Class myClass = Class.forName("tao.xiao.action.A");Field field = myClass.getField("c");System.out.println(field + " ---- " + field.getName() + " ---- " + field.getType());field = myClass.getField("d");System.out.println(field + " ---- " + field.getName() + " ---- " + field.getType());}}

The running result is

public float tao.xiao.action.A.c ---- c ---- floatpublic double[] tao.xiao.action.A.d ---- d ---- class [D

Getting and setting fields values

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.