Use Java reflection mechanism to read configuration files for dynamic class loading and dynamic type conversion

Source: Internet
Author: User

54dabang

In the spring learning process, we can see the benefits of dynamically managing bean objects through configuration files ( loose coupling allows the scattered parts to form a whole, and the whole does not care about the details of each other, thus achieving true physical evacuation coupling, not logic, With the IOC, we can let spring act as the integrator in each frame, and combine the technical framework perfectly.

An important mechanism of spring implementation is to read the configuration file through reflection (Java.lang.reflect) and dynamically generate the class object in the configuration file through the configuration file. Java The dynamic load class is designed to perform different functions without changing the main program code, by modifying the configuration file to manipulate different objects .

Because Java is a strongly typed language, this paper presents a feasible method and idea to realize dynamic type conversion according to a foreigner's blog.

This article mainly helps you to complete the learning goal:

(1) The reflection mechanism is the most basic learning.

(2) Read the configuration file with the most basic Java regular expression to get the required information.

(3) Simulate spring's IOC mechanism to implement dynamic loading of classes.

(4) give the program source code, test, summary

(5) Using the Java reflection mechanism to implement dynamic type conversion (pending completion)

The most basic learning of a Java reflection mechanism

(1) The most basic learning of the Java reflection mechanism can refer to the blog

http://blog.csdn.net/xiaoxian8023/article/details/9206055, the content is more detailed. However, in this article, the method can only be looked up according to MethodName, unable to find the overloaded method (based on the parameter lookup).

Here are two ways of listing:

A) Find and invoke parameters only by the name of the method: the parameters required to invoke the instance method name method of the invoked object

public Object Invokemethodgernaral (Object owner,string Methodname,object[]args)    {     //a. Get the class to which the object belongs first   Ownerclass=owner.getclass ();       Method Method=null;       Object Result=null;        B. Get the method that needs to be called for       (Method M:ownerclass.getdeclaredmethods ())       {       if (M.getname (). Equalsignorecase ( MethodName))       {       method=m;       break;       }       }       try {       //c. Invoke the method   Result=method.invoke (owner, args);//Call Method   } catch (Illegalaccessexception e) {   // Todo auto-generated catch block   e.printstacktrace ()   } catch (IllegalArgumentException e) {   //TODO Auto-generated Catch block   e.printstacktrace ();   } catch (InvocationTargetException e) {   //TODO Auto-generated Catch block   e.printstacktrace ();   }       return result;   }

B) Find and invoke parameters only by exact matching of the name and parameters of the method: the parameters required for the type method invocation of the instance method name parameter of the invoked object

<pre name= "code" class= "Java" >public object InvokeMethod (Object owner,string methodname,class[]clz,object[] args) throws Exception {      //a. To get the object class        Ownerclass=owner.getclass ();    B. Get a method of the class based on the method name and the parameter name methods       Method=ownerclass.getmethod (METHODNAME,CLZ);//The second parameter is obtained by type to have a disadvantage is that the parameter type must be filled in    //c. Methods      for executing an object Object Result=method.invoke (Owner,args); You must have a class object to call    //d. Output result information      System.out.println ("Result return value:" + result);      return result;  }  

The second is to read the configuration file through the most basic Java regular expression to obtain the required information.

From the configuration file to read the information, mainly using the IO stream operation, relatively simple. To make it easy for everyone to understand, I'll simplify this as a string, and then use regular expressions to extract information from it.

For a detailed study of regular expressions, refer to my blog:

http://blog.csdn.net/leixingbang1989/article/details/26486927

For example, to match a string of type:

<metahttp-equiv= "Content-type" content= "text/html; charset=UTF-8">

Where the red part is the data you want to get, note that the length of the data to be obtained is not fixed and may be Unicode

Gb2312 and other encoding types, where we want to get the encoding method.

Here's the simplest piece of code:


public static string parse (string s) {    pattern pattern =pattern.compile ("charset= (. +?) \"");    Transfer characters (. +?) are also added to the wildcard character. Represents what to look for    Matcher Matcher=pattern.matcher (s);    while (Matcher.find ())    {       System.out.println (Matcher.group (1));    }    return s;}

Three simulation of spring's IOC mechanism, read the configuration file, implement the dynamic loading of the class

One of the spring configuration file formats is as follows:

<beans><bean id= "U" class= "Com.bjsxt.dao.impl.UserDAOImpl" ></bean><bean id= "UserService" class= "Com.bjsxt.service.UserService" ><property name= "Userdao" bean= "U"/></bean></beans>

We can use pattern pattern =pattern. Compile ("<beans> (. +?) </beans> ") to get the Bean object configuration information, and then use the regular expression again to get each bean information.

Here I have customized a profile information and put it into a string.

Its configuration format is: property name: Value,

String configure= "class:com.bjsxt.service.school,method:getstudentinfo,args:tom,argstype:java.lang.string";// Format fixed you can use regular expressions to extract string []split={":", ","};//format is   name:value, so the delimiter is:, Parsedata p=new parsedata (Configure);// Implement a regular expression to extract the required string//(1) Get the class name Method name parameter parameter type information  string classname= p.getinfo ("Class", split);    String methodname=p.getinfo ("Method", split);    String arg=p.getinfo ("args", split);    Object []args={arg}; String argstype=p.getinfo ("Argstype", split);

Fourgive the program source code, test, summary
Package Com.bjsxt.service;import Java.lang.reflect.invocationtargetexception;import Java.lang.reflect.Method; public class Dynamicinvocation {public static void main (string[] a) throws Exception {String configure= "class:com.b Jsxt.service.school,method:getstudentinfo,args:tom,argstype:java.lang.string ";//format fixed you can extract String []split={] with regular expressions  : ",", "};//format is Name:value, so the delimiter is:, Parsedata p=new parsedata (Configure);//implementation method for regular expression extraction Required string//(1) Get class name Method name parameter parameter type information    String classname= p.getinfo ("Class", split);    String methodname=p.getinfo ("Method", split);    String arg=p.getinfo ("args", split);    Object []args={arg}; String argstype=p.getinfo ("Argstype", split);//(2) Create an Unknown object instance, object S=class.forname (ClassName). newinstance ();// Note that the object we are currently creating does not know its type//(3) method call//3.1 only finds the lookup method through the method name and calls the disadvantage: there may be a method that is overloaded dynamicinvocation inv=new dynamicinvocation (); Inv.invokemethodgernaral (S, MethodName, args)//3.2 by method name and parameter lookup method and call Class Cls=class.forname (Argstype); System.out.println (Cls.getname ()); Class []CLZ={CLS};INV. InvokeMethod (S, MethodName, CLZ, args);//(4) dynamic coercion type conversion Class intclass=class.forname ("Java.lang.Integer");   System.out.println (Integer.class);}   public Object Invokemethodgernaral (Object owner,string Methodname,object[]args)//Find only through the name of the method and call {//a. Gets the class to which the object belongs first       Class Ownerclass=owner.getclass ();       Method Method=null;        Object Result=null; B. Get the method that needs to be called for (Method M:ownerclass.getdeclaredmethods ()) {if (M.getname (). Equalsignorecase (MethodName       )) {method=m;       Break   }} try {//c. Call the method Result=method.invoke (owner, args);//Call Method} catch (Illegalaccessexception e) {   TODO auto-generated Catch block E.printstacktrace ();   } catch (IllegalArgumentException e) {//TODO auto-generated catch block E.printstacktrace ();   } catch (InvocationTargetException e) {//TODO auto-generated catch block E.printstacktrace ();   } return result; } public Object InvokeMethod (object owner,string METHODNAME,CLASs[]clz,object[] args) throws Exception {//a. Get the Object class Ownerclass=owner.getclass (); B. Get a method of the class based on the method name and the parameter name methods Method=ownerclass.getmethod (METHODNAME,CLZ);//The second parameter is obtained by typing a disadvantage is that the parameter type must be filled in//c. The method of executing an object Result=method.invoke (Owner,args);      You must have a class object to call//d. Output result information System.out.println ("Result return value:" + result);  return result; }  }

Package Com.bjsxt.service;import Java.util.regex.matcher;import Java.util.regex.pattern;public class ParseData { Private String strsource;//Data source public parsedata (String s) {this.strsource=s;} Public  string GetInfo (String name,string []split)//name, value, delimiter {String str=name+split[0]+ "(. +?)" +SPLIT[1]; System.out.println (str);  Pattern pattern =pattern.compile (str);//matching mode  Matcher matcher=pattern.matcher (This.strsource); String value= ""; Boolean isfind=false;if (Matcher.find ())    {value=matcher.group (1);    } else//may be the last character    {    pattern=pattern.compile (name+split[0]+ "(. +?)") + "$");//$ is indicated as a limited end        matcher=pattern.matcher (this.strsource);    if (Matcher.find ())    {    value=matcher.group (1);    }        } return value;}}

V. Using the Java Reflection mechanism to implement dynamic type conversions (pending completion)

The main realization idea comes from a foreigner's blog:

Http://prajith-javatechnical.blogspot.in/2014/09/casting-java-object-dynamically-using.html

As the teacher assigned me a task today, I will translate the blog into Chinese and parse it in the future with time.


Use Java reflection mechanism to read configuration files for dynamic class loading and dynamic type conversion

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.