First introduce several concepts:
1. The concept of Java reflection
Reflection meaning: You can get a running Java object.
2, the function of Java reflection
1) You can determine the class to which the run-time object belongs
2) You can determine the member variables and methods that run-time objects have
3) A method that can even be called to private by reflection
4) Generate dynamic agent
3. Classes that implement Java reflection
1) Class: It represents classes and interfaces in a running Java application
2) Field: Provides information about the properties of a class or interface, as well as its dynamic access rights
3) Constructor: Provides information about a single construction method of a class and access to it
4) Method: Provides information about one of the methods in a class or interface
Note: The class class is the most important feature class in Java reflection, and all information that gets the object (including: Method/property/constructor/access) needs it to implement
4. Steps to write the Java Reflector program:
1) You must first obtain the class object
For example:
Class C1 = Test.class;
Class C2 = class.forname ("Com.reflection.Test");
Class C3 = New Test (). GetClass ();
2) Then call the methods in the class object to get the structure of the properties/methods/constructors of a class
Note: If you want to be able to get a normal method/property/constructor in the class, you should focus on the following reflection classes
Field
Constructor
Method
The principle of the relatively clear recommendation of this article http://www.cnblogs.com/gulvzhe/archive/2012/01/27/2330001.html
The following example demonstrates assigning a value to a variable by reflection
1 PackageOrg.tianchi.userItem;2 3 ImportJava.lang.reflect.Field;4 5 Public classPrivatetest {6 PrivateString name = "Hello"; 7 Public LongNumber ;8 9 PublicString GetName () {Ten returnname; One } A - Public voidsetName (String name) { - This. Name =name; the } - - Public Static voidMain (string[] args)throwsException { -Privatetest pt =Newprivatetest (); + -Class<privatetest> clazz = privatetest.class; + AField field = Clazz.getdeclaredfield ("name"); atField.setaccessible (true); -Field.set (PT, "World")); -Field.setaccessible (false); - -Field fieldnum = Clazz.getdeclaredfield ("number"); -Fieldnum.setaccessible (true); inFieldnum.set (PT, 20); -Fieldnum.setaccessible (false); to + System.out.println (Pt.getname ()); - System.out.println (pt.number); the } *}View Code
2. Use reflection to create an instance of a class that cannot be instantiated by new and invoke its private method for data passing (this is reprinted http://www.cnblogs.com/pricks/archive/2009/08/11/1543855.html)
1 first, create a class that cannot be instantiated: Customer.java:2 Public classCustomer {3 Private LongID;4 PrivateString name;5 PrivateString age;6 7 Private StaticCustomer instance =NULL;8 /**The display declares the constructor as private, and the outside world cannot instantiate the class with new*/9 PrivateCustomer () {}Ten Private Static synchronizedCustomer getinstance () { One if(Instance = =NULL){ A return NewCustomer (); - } - returninstance; the } - - /**this set () method is a private method and cannot be assigned directly to the ID attribute*/ - Private voidSetId (LongID) { + This. ID =ID; - } + Public LonggetId () { A returnID; at } - /**this set () method is a private method and cannot be assigned directly to the Name property*/ - Private voidsetName (String name) { - This. Name =name; - } - PublicString GetName () { in returnname; - } to /**this set () method is a private method and cannot be assigned directly to the Age property*/ + Private voidsetage (String age) { - This. Age =Age ; the } * PublicString getage () { $ returnAge ;Panax Notoginseng } - } the + Next, you start by creating the class instance with reflection, calling its privatization method to assign a value to its property, and finally calling its exposed method to verify that its properties are assigned a value: A ImportJava.lang.reflect.Field; the ImportJava.lang.reflect.Method; + - Public classTest { $ Public Static voidMain (string[] args) { $ //to create an instance of a class -Java.lang.Class C =NULL; -Customer customer =NULL; the Try{ -c = Customer.class;WuyiMethod m1 = C.getdeclaredmethod ("getinstance"); theM1.setaccessible (true);//This sentence is critical, not set to true to get a private method -Customer =(Customer) M1.invoke (c); Wu}Catch(Exception e) {} - About Try{ $Java.lang.reflect.Field FieldID = Customer.getclass (). Getdeclaredfield ("id");//gets the private member variable ID - - //Get Private method SetID (int id) -String firstletter = Fieldid.getname (). substring (0, 1). toUpperCase (); AString setName = "Set" + Firstletter + fieldid.getname (). SUBSTRING (1); +String getName = "Get" + Firstletter + fieldid.getname (). SUBSTRING (1); theJava.lang.reflect.Method Setmethod = Customer.getclass (). Getdeclaredmethod (SetName,NewClass[]{fieldid.gettype ()}); -Method GetMethod = Customer.getclass (). Getdeclaredmethod (GetName,Newclass[]{}); $Setmethod.setaccessible (true);//enables private methods to be fetched to theSetmethod.invoke (Customer,Newobject[]{23});//call the private method and pass the data the theSystem.out.println ("-------------the ID value obtained by public method:" +Customer.getid ()); theSystem.out.println ("-------------the ID value obtained by reflection:" + getmethod.invoke (Customer,NULL)); - in //This section of the code below will be modeled by reflection to assign values to the two private member variables, name and age, respectively . theField fieldName = Customer.getclass (). Getdeclaredfield ("name"); theFirstletter = Fieldname.getname (). substring (0, 1). toUpperCase (); AboutSetName = "Set" + Firstletter + fieldname.getname (). SUBSTRING (1); theSetmethod = Customer.getclass (). Getdeclaredmethod (SetName,Newclass[]{Fieldname.gettype ()}); theSetmethod.setaccessible (true); theSetmethod.invoke (Customer, "Zhang San"); +System.out.println ("-----------------Name:" +customer.getname ()); - theField fieldage = Customer.getclass (). Getdeclaredfield ("Age");BayiFirstletter = Fieldage.getname (). substring (0, 1). toUpperCase (); theSetName = "Set" + Firstletter + fieldage.getname (). SUBSTRING (1); theSetmethod = Customer.getclass (). Getdeclaredmethod (SetName,Newclass[]{Fieldage.gettype ()}); -Setmethod.setaccessible (true); -Setmethod.invoke (Customer, "40"); theSystem.out.println ("-----------------Age:" +customer.getage ()); the}Catch(Exception e) {} the } the}View Code
Note here: Java.lang.reflect.Method seems to be a value object, if you pass it to another method and do the processing, and then come out of that method, still keep its original property unchanged, there is no reference to the characteristics of the type object.
At the same time, the customer class here uses a singleton pattern, but if we use a reflection method to instantiate two instances of the object, they do not point to the same reference, for example:
private static Customer test1 () {
Java.lang.Class c = null;
Customer customer = NULL;
try{
c = Customer.class;
Method m1 = C.getdeclaredmethod ("getinstance");
M1.setaccessible (TRUE);//This sentence is critical, not set to true to get a private method
Customer = (customer) m1.invoke (c);
} catch (Exception e) {}
}
public static void Main (string[] args) {
Customer C1 = Test1 ();
Customer C2 = test1 ();
System.out.println ("-----------------------" + c1.equals (C2));
System.out.println ("-----------------------" + (C1 = = C2));
}
After compiling, two are displayed as false.
Java Reflection Instance