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