Get fields by Reflection:
--
When the method is reflected and called, the static method can not pass the object.
Fields are a little different, even static fields require passing objects
The following is a test class: Includes a test entity class: Girl.java, a reflection test Demo.java
Girl.java:
1 PackageCn.rt.gwq;2 3 Public classGirl {4 5 Private intAge = 18;6 Public intHeight = 168;7 Public StaticString name = "Alice" ;8 9 PublicGirl () {Ten //TODO auto-generated Constructor stub One } A - PublicGirl (intAgeintheight,string name) { - This. Age =Age ; the This. Height =height; - This. Name =name; - } - +}
Demo_fieldrflt:
1 PackageCn.rt.gwq;2 3 ImportJava.lang.reflect.Field;4 5 Importorg.junit.Test;6 7 Public classDemo_fieldrflt {8 9 /**Ten * Reflection Get field One * @throwsException A */ - @Test - Public voidTest1 ()throwsexception{ the -Girl Girl =NewGirl (18,168, "Alice"); - - //Load Class +Class clazz = Class.forName ("Cn.rt.gwq.Girl"); - + //Public Fields AField height = Clazz.getfield ("height"); at intH = (int) Height.get (girl); - - //Private Fields -Field age = Clazz.getdeclaredfield ("Age"); -Age.setaccessible (true); - intA = (int) Age.get (girl); in - //static fields toField name = Clazz.getfield ("name"); +String n =(String) name.get (girl); - the //Output Validation *System.out.println ("Name:" +n+ ", Age:" +a+ ", Height:" +h); $ }Panax Notoginseng -}
Anatomy Field of Java Reflection