Preface
Reflection provides a dynamic function, which is very powerful. It is mainly reflected in the reflection-related API, you can know a strange
All information about the Java class, including properties, methods, constructors, and so on. And elements can be created or called dynamically at run time without having to
The JVM is determined when it runs. Through the review of relevant information, and organized, this article is based on the following article to expand.
"http://blog.csdn.net/mark_yangs/article/details/47427037"
What is the principle of reflection?
Strictly speaking, Java is not a dynamic language, it is not as flexible as Perl and Python. However, the reflection mechanism of Java makes it appear to move
State.
In general, if you want to generate an object of this class, the JVM running the program will confirm that the class object is already loaded. If
has not yet been loaded, the JVM will look up the. class file based on the class name and load it, once the class object is loaded into memory, it can be used to create a
All objects of this class are built.
In addition, for a reference of an unknown type, it is common to use the form of coercion type conversion to get the type reference that the developer wants, if the execution
A wrong type conversion, a ClassCastException exception is thrown.
in the above two processes, the class has been working. Because the class class instance contains all the information for a Java class, including the class name, party
Laws, attributes, and so on. In other words, the class object is the one that represents a class.
Java uses class classes to represent all classes, which makes it easier for developers to take control of class information. Through class, developers can get properties, methods, constructs
modifiers, and other information. After this information is dynamically obtained, the developer can use the class to create an instance, invoke any method, access any property
And so on, these are also the main uses of reflection.
The reflection mechanism-related APIs are mainly concentrated under the Java.lang.reflect package, and the developer is using the interfaces and classes under the package for related reflection
Development. Most frameworks, such as struts, Hibernate, and spring, frequently use the reflection API to perform their dynamic functions.
what is the meaning and function of class
Class classes play a key role in the reflection mechanism, which is the gateway for developers to develop reflection. From above you can tell that class is used to remember
Record a class of information that is created with the loading of the class. So, when will the class be loaded into the JVM? Generally speaking, an ordinary
Java classes, which are loaded into the JVM in the following cases.
(1) You need to use this class to create an object. The following code causes the Stundent class to be loaded into the JVM class:
Student mstudent=new Student ();
(2) To access the static members of the class, the instance code is as follows:
public class Student {static int count=2;}
public class Main {public static void main (string[] args) {System.out.println (Student.count);}}
(3) Dynamically load a class with the specified class name using the class's Static forname () method. If the class is not found, throw
ClassNotFoundException exception, the instance code is as follows:
public class Main {public static void main (string[] args) throws ClassNotFoundException {class Clazz=class.forname ("COM.E Xample.bill.Student ");}}
Regardless of the form, once the class is loaded into the JVM, it creates an instance object of class for it. Then, the developer
How do I get this class object? To summarize, there are several ways to get a class object.
(1) The return value of the class's forname () method is the class type, which is a reference to the class object of the dynamically imported classes. The end of the forname () method
The whole definition is as follows:
public static class<?> forname (String className) throws ClassNotFoundException
(2) Each class will have a static property called Class, through which it is also possible to get to the class object, the instance code is as follows:
Class<student> Clazz=student.class;
(3) The object class has a member method named GetClass, which returns the class object of the object's run-time class. Because the object class is all
class, so all objects can use this method to get the class object of its runtime classes, with the following instance code:
public class Main {public static void main (string[] args) throws ClassNotFoundException {Student mstudent=new Student (); Class<student> clazz= (class<student>) Mstudent.getclass ();}}
After you get to the class object, you can call some of its member methods to get information about the properties, methods, modifiers, and so on of the class it represents.
and call the Newinstance () method to create a new instance object, along with some other functional methods.
how to manipulate member variables of a class
The field class, which represents the property (field) of a class, is also known as a member variable. The reflection can get to its object, the Field object through the class
The Getdeclaredfield () or Getdeclaredfields method is obtained, under the Java.lang.reflect package. field provides a single field about a class or interface
Information, as well as dynamic access to it, the reflected field may be a static field or field of an instance.
Field methods are mainly divided into two classes, namely GetXXX and setxxx. Where getxxx is the value of the field used to get an object, and there is a
For example, GetFloat (), while setxxx is used to set values, they typically have two parameters, one is an object reference and the other is
The value that needs to be set.
The following is an example of using a field to compare the size of two objects by reflection:
public class Fieldtestclass {public String name;public int age;public fieldtestclass (String name,int age) {super (); This.name=name;this.age=age;}}
public class Main {public static void main (string[] args) throws ClassNotFoundException {Fieldtestclass obj1=new fieldtest Class ("Bill1", 100); Fieldtestclass obj2=new fieldtestclass ("Bill2", 200); System.out.println (Compare (Obj1, obj2). name);} private static Fieldtestclass compare (Fieldtestclass obj1,fieldtestclass obj2) {try {Field field1=obj1.getclass (). Getdeclaredfield ("Age"); Field Field2=obj2.getclass (). Getdeclaredfield ("age"); int val1= (integer) field1.get (obj1); int val2= (integer) Field2.get (OBJ2); if (Val1>val2) {return obj1;} Else{return obj2;}} catch (Nosuchfieldexception e) {e.printstacktrace ();} catch (SecurityException e) {e.printstacktrace ();} catch ( IllegalArgumentException e) {e.printstacktrace ();} catch (Illegalaccessexception e) {e.printstacktrace ();} return null;}}
The above code output results are: bill2
It is important to note that if we set the age in Fieldtestclass to private, which is a proprietary property, the program will report
Illegalaccessexception exception.
How to manipulate the class method
Method class, which represents the methods of the class. Like field, reflection can get to its object, the way it's used is dynamic call, method
Objects are obtained through the class GetMethod () or GetMethods () method, and also under the Java.lang.reflect package, method provides information about the class or interface
Information about a method (and how to access the method) in a method that might be a class method or an instance method, including an abstract method.
The most-used method in the methods class is Invoke (), which means the method call. It's first argument is an instance of the class that is represented by class
Object, which is later an indeterminate argument list of type object, which is the parameter list that the method object represents.
The following is a usage instance of a method that implements the dynamic invocation of the methods through command-line arguments:
public class Methodtestclass {public void M1 () {System.out.println ("M1 ...");} public void m2 () {System.out.println ("m2 ...");}}
public class Callmethodtest {public static void main (string[] args) {args = new string[] {"M1"}; String methodName = args[0];if (methodName! = null) {class<methodtestclass> Clazz = methodtestclass.class;try {Meth OD m = Clazz.getdeclaredmethod (MethodName), if (M! = null) {Methodtestclass obj = clazz.newinstance (); M.invoke (obj);}} catch (Nosuchmethodexception e) {e.printstacktrace ();} catch (SecurityException e) {e.printstacktrace ();} catch ( Instantiationexception e) {e.printstacktrace (),} catch (Illegalaccessexception e) {e.printstacktrace ();} catch ( IllegalArgumentException e) {e.printstacktrace (),} catch (InvocationTargetException e) {e.printstacktrace ();}}}}
The above code output result: M1 .....
Note that if the specified method name does not exist, the program will report the nosuchmethodexception exception, if the permissions of the method are set to private, i.e. private
when there is a property, the program will report Illegalaccessexception exception.
How to access private members of a class using the reflection mechanism
According to the syntax rules of Java, private members of a class (including private member variables and methods) can only be accessed by internal methods. However, by reflecting
Mechanism, you can access all members of a class, including private members.
If the developer is developing a reflection mechanism program, treat private members like public members, then you will encounter an exception thrown, the following program
You can access private members:
public class Privatetestclass {private string Field;public privatetestclass (String field) {super (); This.field=field;}}
public class Privatetest {public static void main (string[] args) throws Nosuchfieldexception, SecurityException, Illegala Rgumentexception, illegalaccessexception {privatetestclass obj=new privatetestclass ("Bill"); Class Clazz=obj.getclass (); Field F=clazz.getdeclaredfield ("field"); F.setaccessible (true);//access is set to TrueSystem.out.println (F.get (obj));}}
Program output Result: Bill
From the above code, the private member Variable field can be successfully accessed. Where the key line of code is called field
The Setaccessible () method allows the field property to become accessible.
--------------------------------------------------------------------------------------------------------------- ----------------------------------------
Reprint Please specify the Source: http://blog.csdn.net/hai_qing_xu_kong/article/details/47614679 Emotional Control
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
The reflection mechanism of Java