The effect of reflection mechanism
The general mechanism is that Java knows the definition of the class (such as import the class, or just in the same package), and then goes to the new instance according to the class definition. And the reflection mechanism does not know what the class is, according to the class name such as the string to get an instance, and then according to the method name to execute the method. Like saying, the general picture of a tiger, I have to know what the tiger looks to draw out, with the reflection mechanism, I just know the name "Tiger" can be drawn out, you can know what the tiger eat, what ability, what attributes.
function of the reflection mechanism
(These classes are located in the Java.lang.reflect package)
Class: Represents a Class. (Java.lang.Object java.lang.class<t>T-the type of class that is modeled by this class object.) For example, the type of String.class is class<string>. If the class being modeled is unknown, use class<?>. )
Field class: Represents a member variable of a class that provides information about a single field of a class or interface, and the dynamic access rights to it. The reflected field may be a class (static) field or an instance field. )
Method class: Methods that represent classes. ( Method
provides information about a single method (and how to access the method) on a class or interface. The method that is reflected may be a class method or an instance method, including an abstract method. )
Construct class: Represents the construction method of a class. (Provides information about a single construction method of a class and access to it.) )
Array class: Provides dynamic creation of arrays, as well as static methods for accessing elements in an array.
To create a test class
Package Com.gqx.reflect;class Person {private String name;public int, public int add (int para1,int para2) {return para1 +para2;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} public int getage () {return age;} public void Setage (int.) {This.age = age,} public String toString () {return "[" +this.name+ " " +this.age+ "]";} publi C Person (String name, Int. age) { this.age=age; this.name=name; } Public person () { } public string say (String message) {return message;}}
below to start using
Java.lang.Object java.lang.class<t> methods
Package Com.gqx.reflect;import Java.lang.reflect.constructor;import Java.lang.reflect.field;import Java.lang.reflect.invocationtargetexception;import Java.lang.reflect.method;import Java.lang.reflect.Modifier; public class Demo3 {public static void main (string[] args) throws ClassNotFoundException, Nosuchmethodexception, Security Exception, Illegalaccessexception, IllegalArgumentException, InvocationTargetException, Instantiationexception, nosuchfieldexception {//TODO auto-generated method stub//Gets the class object class<?> demo1=class.forname (" Com.gqx.Reflect.Person "); class<?> demo2=new person (). GetClass (); Class<?> demo3=person.class;/** * Get field *///use GetFields Get Property (array of Field object for public field) field[] fields = Demo1.getfields ( ); for (Field f:fields) {System.out.println (f); }//Use Getdeclaredfields to get properties fields = Demo1.getdeclaredfields (); for (Field f:fields) {System.out.println (f); }/** * Gets the method */system.out.println of the Class ("All methods of =============== class ===============");Returns an array containing some method objects that reflect the public member method of the class or interface represented by this class object, including those declared by the class or interface, and those inherited from the superclass and the hyper-interface. Method[] method = Demo1.getmethods (); for (int i = 0; i < method.length; ++i) {class<?> returntype = Method[i].getreturntype (); class<?> para[] = Method[i].getparametertypes (); int temp = Method[i].getmodifiers (); Get modifier System.out.print (modifier.tostring (temp) + ""); Gets the return type System.out.print (Returntype.getname () + ""); Get the method name System.out.print (method[i].getname () + ""); System.out.print ("("); Get c parameter for (int j = 0; j < para.length; ++j) {System.out.print (Para[j].getname () + "+" a RG "+ j); if (J < para.length-1) {System.out.print (","); }}//Whether there is an exception class<?> exce[] = Method[i].getexceptiontypes (); if (exce.lengtH > 0) {System.out.print (") throws"); for (int k = 0; k < exce.length; ++k) {System.out.print (Exce[k].getname () + ""); if (K < exce.length-1) {System.out.print (","); }}}} else {System.out.print (")"); } System.out.println (); }system.out.println (); /** * Gets the constructor */system.out.println of the class ("*****************");//Use Getdeclaredconstructors to get the constructor//returns a containing some An array of Constructor objects that reflect all the public constructor methods of the class represented by this class object. Constructor<?>[] Constructors = demo1.getconstructors (); for (constructor<?> m:constructors) {System.out.println (M); }//using Getdeclaredconstructors to get the constructor constructors = Demo1.getdeclaredconstructors (); for (constructor<?> m:constructors) {System.out.println (M); }/** * The instance of the new class */system.out.println ("*****************");//To invoke the method, you must obtain the method/** * GetMethod (String name, Class<?> ... parametertypes) * Returns a method object that reflects the specified public member methods of the class or interface represented by this class object. *string: The name of the method, *class<?>, ... Parametertypes: The method needs to accept the form of an array of arguments, * because methods in Java are prone to overloading depending on the number of arguments. */object demo=demo3.newinstance (); Method Addmethod=demo3.getmethod ("Add", New class[]{int.class,int.class}), Object Result=addmethod.invoke (demo, new object[]{1,2}); SYSTEM.OUT.PRINTLN (Integer) result);/** * Gets all the properties of a class */system.out.println ("=============== This class attribute ==============="); field[] field = Demo1.getdeclaredfields (); for (int i = 0; i < field.length; i++) {//permission modifier int mo = Field[i].getmodifiers (); String priv = modifier.tostring (MO); Attribute type class<?> type = Field[i].gettype (); System.out.println (Priv + "" + type.getname () + "" + field[i].getname () + ";");} System.out.println ("========== private Property =========="); Gets the implemented interface or parent class Property field[]filed1 = Demo1.getfields (); for (int j = 0; J < Filed1.length; J + +) {//permission modifier int mo = Filed1[j].getmodifiers (); String priv = modifier.tostring (MO); Attribute type class<?> type = Filed1[j].gettype (); System.out.println (priv + "+ type.getname () +" "+ filed1[j].getname () +"; ");}}}
Manipulating the properties of a class through a reflection mechanism
Package Com.gqx.reflect;import Java.lang.reflect.field;public class Demo4 {private String proprety = null;public static V OID Main (string[] args) throws ClassNotFoundException, Instantiationexception, Illegalaccessexception, Nosuchfieldexception, SecurityException {//TODO auto-generated method Stubclass<?> clazz = Class.forName (" Com.gqx.Reflect.Demo4 "); Object obj = clazz.newinstance (); You can assign a value directly to the property of private Field field = Clazz.getdeclaredfield ("proprety"); Field.setaccessible (true); Field.set (obj, "Java Reflection mechanism"); System.out.println (Field.get (obj));}}
Java Reflection mechanism