Android (Java) Learning Note: 109: Get member variables by reflection and use

Source: Internet
Author: User

1  Packagecn.itcast_03;2 3 ImportJava.lang.reflect.Constructor;4 ImportJava.lang.reflect.Field;5 6 /*7 * Get member variables by occurrence and use8  */9  Public classReflectdemo {Ten      Public Static voidMain (string[] args)throwsException { One         //Get bytecode File object AClass C = class.forname ("Cn.itcast_01.Person"); -  -         //get all the member variables the         //field[] fields = C.getfields (); -         //field[] fields = C.getdeclaredfields (); -         //For (Field field:fields) { -         //System.out.println (field); +         // } -  +         /* A * Person p = new person (); p.address = "Beijing"; SYSTEM.OUT.PRINTLN (p); at          */ -  -         //creating an object from a parameterless construction method -Constructor con =c.getconstructor (); -Object obj =con.newinstance (); - System.out.println (obj); in  -         //to get a single member variable to         //get address and assign value to it +Field Addressfield = C.getfield ("Address"); -         //Public void Set (Object obj,object value) the         //sets the field that is represented by this field object on the specified object variable to the specified new value.  *Addressfield.set (obj, "Beijing");//set the value for the Addressfield field of the Obj object to "Beijing" $ System.out.println (obj);Panax Notoginseng  -         //get the name and assign a value to it the         //nosuchfieldexception +Field NameField = C.getdeclaredfield ("name"); A         //illegalaccessexception theNamefield.setaccessible (true); +Namefield.set (obj, "Brigitte"); - System.out.println (obj); $  $         //get age and assign a value to it -Field Agefield = C.getdeclaredfield ("Age"); -Agefield.setaccessible (true); theAgefield.set (obj, 27); - System.out.println (obj);Wuyi     } the}

Android (Java) Learning Note: 109: Get member variables by reflection and use

Related Article

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.