What is the difference between the introspection mechanism and the reflection mechanism of Java
Introspective operations are only for JavaBean, and only members of classes that conform to the JavaBean rule can operate with the introspection API .... While reflection is different, all members of a class can perform reflection operations.
Introspection and reflection operation is also very different, introspection is to get the attribute descriptor Propertydecriptor before doing various operations, reflection is to get the class bytecode class before doing various operations.
Reflection (Reflection) (for scalabilityIntelligent)
In contrast, reflection is a little easier to understand than introspection. In a relatively white word, reflection is the technique by which you can get objects (classes, properties, methods) by name. For example, we can use the class name to generate an instance of a class, know the method name, you can call this method, know the property name can access the value of this property, or write two examples to give you a more intuitive understanding of how reflection is used:
// to construct an instance of a class from a class name Classclasscls_str=class.forname ("java.lang.String"); // It looks familiar, because people who have used JDBC to access the database have used J . objectstr=cls_str.newinstance (); // equivalent to stringstr=newstring () ; // to invoke a method by means name Stringmethodname= "Length"; METHODM=cls_str.getmethod (methodName,null); System.out.println ("Lengthis" +m.invoke (str,null)); // equivalent to System.out.println (Str.length ()) ;
The above two examples are more commonly used methods. Seeing the example above, there is a question: why bother? Why is it so complicated to be done in a single statement? Yes, there is really no need for such trouble in the above example. But you imagine an application that supports dynamic feature extensions, which means that the program does not restart but can automatically load new functionality, which is represented by a specific class. First we have to define an interface class for these functions, and then we ask that all extended function classes have to implement the interface I specify, which defines the interface rules between the application and the extensible functionality, but how does it load dynamically? We have to let the application know the class name of the feature class to be extended, such as Test. FUNC1, when we tell the application of the class name (string), it can use the method of our first example to load and enable the new functionality. This is the reflection of class, do you have any other choice?
Application: Implementing dynamic loading of classes with reflection in Java
// first define an interface to isolate the class: Public Interface operator{//Public java.util.List Act (java.util.List params); Public
Based on the principle of design patterns, we can write different classes for different functions, each inheriting the operator interface, and the client only needs to program on the operator interface to avoid a lot of trouble. For example, this class:
ImportJava.util.*; Public classSuccessImplementsoperator{
Public Static voidMain (string[] args) {List List=NewArrayList (); List.add ("SUCCESS3"); Operator op=NewSuccess (); System.out.println ("act===" + op.act ("Success1", "Success2", list));}//ways to implement an interface//Public Java.util.List Act (java.util.List params) PublicJava.util.List Act (string content, string content2,java.util.list params) {List result=NewArrayList (); Result.add (content); Result.add (Content2); Result.add (params); returnresult;}}
Similarly, you can write another class:
ImportJava.util.*; Public classLoadImplementsoperator{ Public Static voidMain (string[] args) {List List=NewArrayList (); List.add ("Load3"); Operator op=NewLoad (); System.out.println ("act===" + op.act ("Load1", "Load2", list));}//Public Java.util.List Act (java.util.List params) PublicJava.util.List Act (string content, string content2,java.util.list params) {List result=NewArrayList (); Result.add (content); Result.add (Content2); Result.add (params); returnresult;}}
We can also write a lot of other classes, but there is a problem, the interface is not instantiated, we have to manually control which class is specifically instantiated, it is very uncomfortable, if you can pass a parameter to the application, let yourself choose to instantiate a class, execute its act method, then our work is much easier
Fortunately, Java provides such a reflection mechanism that can achieve our unreasonable requirements. Write a configuration file emp.properties:
#成功响应
1000=success
#向客户发送普通文本消息
2000=load
#客户向服务器发送普通文本消息
3000=store
The key name in the file is the message header that the customer will send to me, the customer sends 1000 to me, then I execute the Act method of the Success class, similarly if send 2000 to me, then execute the Load Class act method, so that the system is fully compliant with the open and closed principle, if you want to add new features, There is no need to modify the existing code, just to add the corresponding rule in the configuration file, and then write a new class, the implementation of the Act method is ok, even if I leave the project, it will be well extended in the future. Such a system has a very good extensibility and pluggable nature.
The following example shows the function of dynamic loading, in which the program does not know which class to instantiate in the process.
Importjava.lang.reflect.*;Importjava.util.Properties;ImportJava.io.FileInputStream;Importjava.util.List;//This program is programmed for operator, so there is no need to make any changes to directly provide the load and store classes,can support 2000, 3000 invocation of parameters//with such a reflection mechanism, the function of the interface can be played to the extreme, the design pattern is also more capable of manifesting the power, Public classtestreflect{//load configuration file, query the message header corresponding class namePrivatestring Loadprotocal (string header) {string result=NULL; Try{Properties prop=NewProperties (); //fileinputstream fis=new fileinputstream ("emp.properties"); //id = prop.getproperty (idstring); //prop.load (FIS); //fis.close ();Prop.load (GETTCL (). getResourceAsStream ("Emp.properties")); Result=Prop.getproperty (header); }Catch(Exception e) {System.out.println (e); }returnresult;}Private StaticClassLoader GETTCL ()throwsIllegalaccessexception,invocationtargetexception {Method Method=NULL; Try{method= Thread.class. GetMethod ("Getcontextclassloader",NULL); } Catch(nosuchmethodexception e) {return NULL; }return(ClassLoader) Method.invoke (Thread.CurrentThread (),NULL);}//respond to messages, import the corresponding classes with reflection Publicstring Response (string header,string content,string content2,list List) {string result=NULL; String s=NULL; Try { /** Import the property file Emp.properties, query the name of the class corresponding to the header * through the reflection mechanism to dynamically load the matching class, all classes are operator interface isolation * can be modified by modifying the properties file, add a new class (Inherit Msgoperator interface) to extend the Protocol*/s= "Org.bromon.reflect." + This. Loadprotocal (header). Trim (); //Load ClassSystem.out.println ("s===" +s);//Print s===org.bromon.reflect.successClass c=Class.forName (s); //Java.lang.reflect.Methods is a class used to describe a single method in a class//Method m[] = C.getdeclaredmethods ();// //for (int i = 0; i < m.length; i++)// //System.out.println (m[i].tostring ()); //Print public java.util.List org.bromon.reflect.Success.act (java.util.List)//to create a case for a classOperator mo=(Operator) c.newinstance (); System.out.println ("mo===" +mo); //constructing a parameter listClass params[]=NewClass[3]; //params[0]=class.forname ("java.util.List");Params[0]=class.forname ("Java.lang.String"); params[1]=class.forname ("Java.lang.String"); params[2]=class.forname ("Java.util.List"); System.out.println ("params[0]===" +params[0]); // //querying the Act methodMethod M=c.getmethod ("act", params); System.out.println ("method==" +m.tostring ()); Object[] args=NewObject[3]; args[0]=content; args[1]=Content2; args[2]=list; // //call the method and get the returnObject Returnobject=m.invoke (Mo,args);//This place is a problem.//System.out.println ("returnobject===" +returnobject);List RESULT2 =(List) returnobject; Result= (String) result2.get (0); System.out.println ("result2==" +result2); //}Catch(Exception e) {System.out.println ("Handler-response:" +e); //handler-response:java.lang.illegalargumentexception:argument Type mismatch//IllegalArgumentException-If the method is an instance method, and the specified object parameter is not an instance of the class or interface (or the subclass or the implementation program) that declares the underlying method;//If the number of arguments and parameters is not the same, if the unpacking conversion of the base parameter fails, or if after unpacking, the parameter value cannot be converted to the corresponding formal parameter type through the method call transformation. }returnresult;} Public Static voidMain (String args[]) {testreflect TR=NewTestreflect (); List List=Newjava.util.ArrayList (); List.add ("Test List"); Tr.response ("A", "Load1", "Load2", list);//1000 is success,2000 is loadTr.response ("n", "Success1", "Success2", list);//1000 is success,2000 is load}}
Test it, run it. Testreflect class, print content, great!!
Result2==[load1, Load2, [Test list]]
Result2==[success1, SUCCESS2, [Test list]]
This program is for operator programming, so there is no need to make any changes, directly provide the load and the store class, you can support 2000, 3000 to make the call of parameters.
With such a reflection mechanism, the function of the interface can be exerted to the extreme, and the design pattern is more capable of manifesting the power.
Introspection (Introspector)
Introspective operations are only for JavaBean, only members of classes that conform to JavaBean rules can be manipulated using the introspection API
Introspection is a default processing method of the Java language for Bean class properties and events. For example, there is a property name in Class A, so we can get its value by Getname,setname or set a new value. The Name property is accessed through Getname/setname, which is the default rule. Java provides a set of Getter/setter methods used by the API to access a property that allows you to not need to know the rules, which are stored in the package Java.beans.
The general practice is to obtain the BeanInfo information of an object through the class Introspector, and then beaninfo to get the descriptor of the property (PropertyDescriptor), through which the property descriptor can obtain a corresponding getter/ Setter method, and then we can call these methods. Let's take a look at an example that prints out all the property names and values for an object:
/**createdon2004-6-29*/ Packagedemo; ImportJava.beans.BeanInfo; ImportJava.beans.Introspector; ImportJava.beans.PropertyDescriptor; Public classintrospectordemo{String name; Public Static voidMain (String[]args) throwsexception{
Introspectordemo Demo=NewIntrospectordemo (); Demo.setname ("Winterlau"); //If you don't want to list the attributes of the parent class,//The second parameter of the getbeaninfo fills in the information of the parent classBeanInfo Bi=introspector.getbeaninfo (Demo.getclass (), Object.class);//to get beaninfo information for an object through class IntrospectorPropertydescriptor[] Props=bi.getpropertydescriptors ();//to get the descriptor of a property by BeanInfo for(inti=0;i<props.length;i++){ //This property descriptor allows you to obtain a Getter/setter method for a property.//then we can invoke these methods through the reflection mechanism.System.out.println (Props[i].getname () + "=" +props[i].getreadmethod (). Invoke (Demo,NULL)); } } PublicString GetName () {returnname;} Public voidSetName (stringname) { This. name=name;} }
Application:To map data in a form to the properties of a class through an introspective mechanism
The Formbean in struts in the Web development framework is to map the data in the form to the properties of the class through an introspective mechanism , so there is a Getter/setter method required for each property of the Formbean. But that's not always the case, what does it mean? That means that for a bean class, I can have no attributes, but as long as there is one of the getter/setter methods, then the introspection mechanism of Java will think that there is a property, such as a method setmobile in a class, then think that there is a property of mobile, This makes it easier for us to define the Bean class through an interface rather than having to care about the implementation and not care about the storage of the data in the bean. For example, we can put all the Getter/setter method into the interface definition, but the real data access is implemented in the specific class, which can improve the system extensibility.
Summarize
Applying the reflection and introspection of Java to program design can greatly provide the expansibility and Intellectualization of the program. There are a lot of projects that take both of these technologies to implement their core functions, such as struts, which we mentioned earlier, and the Digester project for working with XML files, but it should be said that almost all projects are more or less using both techniques. In the actual application process, the two should be combined in order to play a true intelligent and highly scalable.
Understanding the reflection and introspection of Java and its differences