One, what is reflection:
The concept of reflection was first proposed by Smith in 1982, and was primarily a capability for a program to access, detect, and modify its own state or behavior . The proposal of this concept soon triggered the research on the application of reflectivity in Computer science field. It is first used in the field of programming language design, and has achieved achievements in Lisp and object-oriented. Among them, lead/lead++, openc++, Metaxa and Openjava are the language based on reflection mechanism. Recently, the reflection mechanism has also been applied to the Windows system, the operating system and the file system.
Reflection itself is not a new concept, although computer science gives a new meaning to the concept of reflection. In computer science, reflection refers to a class of applications that are self-describing and self-controlling. In other words, this kind of application uses some mechanism to realize the description (self-representation) and monitoring (examination) of its own behavior, and can adjust or modify the state and related semantics of the behavior described by the application according to the state and result of its behavior.
second, what is class reflection in Java:
Reflection Yes One of the characteristics of the Java programming language, which allows the running Java program to check itself, or "self-audit", and can directly manipulate the internal properties and methods of the program. This ability of Java is not used much in practical applications, but there is no such feature in other programming languages at all. For example, there is no way to get information about a function definition in a program in Pascal, C, or C + +.
Reflection is the key to Java being considered a dynamic (or quasi-dynamic) language, allows the program to obtain information about the contents of any known name class within the execution period Reflection APIs , including package , type parameters , superclass , Implemented interfaces , inner classes , outer class , fields , Constructors , methods , modifiers ,
third, the class required in the Java class Reflection:
Java class reflection requires not many classes, respectively: field , constructor , Method , class , object , I'll make a brief description of these classes below. The
field class: provides information about the properties of a class or interface, as well as its dynamic access rights. The reflected field may be a class (static) attribute or an instance property, and a simple understanding can be seen as a class that encapsulates the properties of a reflective class. The
Constructor class : Provides information about a single construction method of a class and access to it. Unlike field classes, the field class encapsulates the properties of the reflection class, while the constructor class encapsulates the method of constructing the reflection class.
Method Class: provides information about a single method on a class or interface. The method that is reflected may be a class method or an instance method, including an abstract method. This class is not difficult to understand, it is a class used to encapsulate the reflection class method.
class: An instance of the class that represents classes and interfaces in a running Java application. An enumeration is a class, and a comment is an interface. Each array belongs to a class that is mapped to a class object, and all arrays that have the same element type and number of dimensions share the class object.
object class: Each class uses Object as the superclass. All objects, including arrays, implement methods of this class.
What can the reflection class of Java do:
After reading the above so much I think you have been impatient, you think I am wasting your time, so good! Let's illustrate it with some simple little examples.
Let's start by looking at what we can get from the reflection mechanism in Java.
First, let's write a class:
Java code
Import Java.awt.event.ActionListener; Import java.awt.event.ActionEvent; Class A extends Object implements actionlistener{ private int A = 3; Public integer b = new integer (4); Public A () {} public a (int. id,string name) {} public int abc (int id,string name) {return 0;} public void actionperformed (ActionEvent e) {} }
You may be confused by my class, you can not see what I want to do, then do not look at this class, this class is used to test, you know that it inherits the object class, there is an interface is ActionListener, two attributes int and integer, two construction methods and two methods, That's enough.
Let's take the Class A as a reflection class and go over some of the information in Class A, first we'll go over the properties and property values in the Reflection class.
Java code
import java.lang.reflect.*; Class b{public static void Main (String args[]) {A r = new A (); Class temp = R.getclass (); try{System.out.println ("All public properties in the Reflection class"); Field[] FB =temp.getfields (); for (int j=0;j<fb.length;j++) {Class cl = Fb[j].gettype (); System.out.println ("FB:" +CL); } System.out.println ("All properties in the Reflection class"); field[] fa = Temp.getdeclaredfields (); for (int j=0;j<fa.length;j++) {Class cl = Fa[j].gettype (); System.out.println ("fa:" +CL); } System.out.println ("Value of private property in Reflection class"); Field f = Temp.getdeclaredfield ("a"); F.setaccessible (TRUE); Integer i = (integer) f.get (R); System.out.println (i); }catch (Exception e) {e.printstacktrace (); } } }
Here are two methods, GetFields (), Getdeclaredfields (), which are used to obtain all of the public and reflection classes in a reflection class. There are also GetField (string) and Getdeclaredfield (string) methods that are used to reflect the properties specified in the class, and note that the GetField method can only take the properties that are public in the reflection class. And the Getdeclaredfield method can be taken.
The field class is also used here.
setaccessiblemethod, which is used to set whether there is permission to access private properties in the reflection class, is only accessible when set to true, and false by default. The field class also has the set (Object Attributename,object value) method, which can change the value of the specified property.
Let's take a look at how to get a construction method in a reflection class
Java code
Import java.lang.reflect.*; public class Sampleconstructor {public static void Main (string[] args) { a r = new A (); Printconstructors (R); } public static void Printconstructors (A r) { Class c = r.getclass (); Gets the class name of the specified class String className = C.getname (); try { //Get the constructor method for the specified class constructor[] theconstructors = C.getconstructors (); for (int i=0; i<theconstructors.length; i++) { //Gets a collection of parameters for the specified construction method class[] Parametertypes = theconstructors[ I].getparametertypes (); System.out.print (ClassName + "("); for (int j=0; j<parametertypes.length; j + +) System.out.print (parametertypes[j].getname () + ""); System.out.println (")"); } } catch (Exception e) { e.printstacktrace ();}} }
This example is simple, just using the GetConstructors () method to get the collection of reflection class construction methods, and get the parameters of the constructor method with the Getparametertypes () of the constructor class.
Let's get back to the parent class (superclass) and interface of the reflection class
Java code
Import java.io.*; Import java.lang.reflect.*; public class Sampleinterface {public static void Main (string[] args) throws Exception { A RAF = new A (); Printinterfacenames (RAF); } public static void Printinterfacenames (Object o) { Class c = o.getclass (); Gets the interface of the Reflection class class[] theinterfaces = C.getinterfaces (); for (int i=0; i<theinterfaces.length; i++) System.out.println (Theinterfaces[i].getname ()); Gets the parent class of the Reflection Class (superclass) class Thesuperclass = C.getsuperclass (); System.out.println (Thesuperclass.getname ()); } }
This example is also very simple, just use the class Getinterfaces () method to get all the interfaces of the reflection class, because the interface can have more than one, so it returns a class array. Use the Getsuperclass () method to get the parent class of the reflection Class (the superclass), because a class can only inherit from a class, so it returns a class object.
Let's take a look at the reflection class method
Java code
Import java.lang.reflect.*; public class SampleMethod {public static void Main (string[] args) { A P = new A (); Printmethods (P); } public static void Printmethods (Object o) { Class c = o.getclass (); String className = C.getname (); method[] m = C.getmethods (); for (int i=0; i<m.length; i++) { //The return type of the output method System.out.print (M[i].getreturntype (). GetName ()); The output Method name System.out.print ("" +m[i].getname () + "("); Gets the parameter of the method class[] parametertypes = M[i].getparametertypes (); for (int j=0; j<parametertypes.length; J + +) { System.out.print (Parametertypes[j].getname ()); if (parametertypes.length>j+1) { System.out.print (","); } } System.out.println (")");}}
This example is not difficult, it just gets all the methods of the reflection class, including the method that inherits from its parent class. It then gets the return type, method name, and method parameters of the method.
Let's go back and think about the properties, constructs, parent classes, interfaces, and methods of the reflection class that can help us do something!!
Below I write a relatively complete small example, to illustrate what the Java reflection class can do!!
Java code
Import Java.lang.reflect.Constructor; Import Java.lang.reflect.Method; public class Loadmethod {public Object Load (String cname,string methodname,string[] type,string[] param) { Object retobj = null; try {//load the specified Java class, CLS = Class.forName (cName); Gets an instance of the specified object Constructor ct = cls.getconstructor (null); Object obj = ct.newinstance (null); The data type of the build method parameter Class partypes[] = This.getmethodclass (type); Gets the specified method in the specified class meth = Cls.getmethod (MethodName, partypes); The parameter value of the build method Object arglist[] = This.getmethodobject (Type,param); Invokes the specified method and gets the return value of the object type retobj= meth.invoke (obj, arglist); }catch (Throwable e) {System.err.println (e); } return retobj; }//Get parameter type class[] method public class[] Getmethodclass (string[] type) {class[] cs = New Class[type.length]; for (int i = 0; i < cs.length; i++) {if (!type[i].trim (). Equals ("") | | Type[i]!=null) {if (type[i].equals ("int") | | Type[i].equals ("Integer")) {cs[i]=integer.type; }else if (type[i].equals ("float") | | Type[i].equals ("Float")) {cs[i]=float.type; }else if (type[i].equals ("double") | | Type[i].equals ("Double")) {cs[i]=double.type; }else if (Type[i].equals ("boolean") | | Type[i].equals ("Boolean")) {cs[i]=boolean.type; }else{Cs[i]=string.class; }}} return CS; }//Get parameter object[] method public object[] Getmethodobject (string[] type,string[] param) {object[] obj = n EW Object[param.length]; for (int i = 0; i < obj.length; i++) {if (!param[i].trim (). Equals ("") | | Param[i]!=null) {if (type[i].equals ("int") | | Type[i].equals ("Integer")) {obj[i]= new integer (Param[i]); }else if (type[i].equals ("float") | | Type[i].equals ("Float")) {obj[i]= new float (param[i]); }else if (type[i].equals ("double") | | Type[i].equals ("Double")) {obj[i]= new Double (Param[i]); }else if (Type[i].equals ("boolean") | | Type[i].equals ("boolean")) {Obj[i]=new Boolean (param[i]); }else{Obj[i] = param[i]; }}} return obj; } }
This is what I wrote at work. Implements Java to load the specified class at run time, and invokes a small example of the specified method. There is no Main method here, you can write one yourself.
The five parameters that the Load method receives are the Java class name, the method name, the type of the parameter, and the value of the parameter.
Conclusion:
Java language Reflection provides a versatile way to dynamically link program components. It allows the program to create and control objects of any class without having to hardcode the target class in advance. These features make reflection especially useful for creating libraries that collaborate with objects in a very common way. Java reflection is useful in that it enables classes and data structures to dynamically retrieve relevant information by name and allows manipulation of that information in a running program. This feature of Java is very powerful and is not available in other commonly used languages such as C, C + +, Fortran, or Pascal.
However, there are two drawbacks of reflection. The first is a performance issue. Used for fields and methods the reflection is much slower than direct code when accessing. The degree of performance issues depends on how the reflection is used in the program. Slow performance will not be a problem if it is part of a program that is relatively rarely involved in running. Even if the worst-case timing chart in the test shows a reflection operation that only consumes a few microseconds. Performance issues become critical only when reflection is used in the core logic of performance-critical applications.
Java Reflection mechanism