Reflection combines XML simple simulation spring to create beans

Source: Internet
Author: User

The bottom of the frame is actually implemented by reflection, just like Spring, when you configure a variety of beans to be configured as a configuration file, which beans you need to match, and the spring container to dynamically load according to your needs , Here is a simple example to simulate:

1. Deepen the understanding of reflection,

2. See how the framework is implemented

3. Parsing of XML by dom4j

Two simple classes:

User:

public class User {private string Username;private  string userpwd;private string Userage;public string Getuserage () { return userage;} public void Setuserage (String userage) {this.userage = Userage;} Public String GetUserName () {return userName;} public void Setusername (String userName) {this.username = UserName;} Public String getuserpwd () {return userpwd;} public void Setuserpwd (String userpwd) {this.userpwd = Userpwd;}}

Student class:

public class Student {private string Stuname;private string Stuno;public string Getstuname () {return stuname;} public void Setstuname (String stuname) {this.stuname = Stuname;} Public String Getstuno () {return stuno;} public void Setstuno (String stuno) {This.stuno = Stuno;}}

Config XML file:<bean-class> inside is the package name of the Class + class name

<?XML version= "1.0" encoding= "UTF-8"?><Beans>    <Bean>        <Bean-name>User</Bean-name>        <Bean-class>Com.bwf.test.User</Bean-class>        <Init>            < Propertyname= "UserName">Zhangsan</ Property>            < Propertyname= "Userage">18</ Property>            < Propertyname= "Userpwd">123456</ Property>        </Init>    </Bean>        <Bean>        <Bean-name>User1</Bean-name>        <Bean-class>Com.bwf.test.User</Bean-class>        <Init>            < Propertyname= "UserName">Lisi</ Property>            < Propertyname= "Userpwd">654321</ Property>            < Propertyname= "Userage">24</ Property>        </Init>    </Bean>        <Bean>        <Bean-name>Student</Bean-name>        <Bean-class>Com.bwf.test.Student</Bean-class>        <Init>            < Propertyname= "Stuname">Wangwu</ Property>            < Propertyname= "Stuno">1</ Property>        </Init>    </Bean>    </Beans>

Parse XML assigns values and tests to objects:

Import Java.io.file;import java.io.fileinputstream;import Java.io.filenotfoundexception;import Java.io.InputStream ; Import Java.lang.reflect.field;import Java.lang.reflect.invocationtargetexception;import Java.lang.reflect.method;import Java.util.list;import Org.dom4j.document;import org.dom4j.DocumentException; Import Org.dom4j.element;import org.dom4j.io.saxreader;import Com.bwf.test.student;import com.bwf.test.User;public Class Xmlrefelct {public static void main (string[] args) {try {ReadXML ();} catch (Exception e) {e.printstacktrace ();}} /** * Read XML file * @throws Exception */public static void ReadXML () throws Exception{inputstream in = null;try {in = new file InputStream (New File ("Src/spring.xml"));} catch (FileNotFoundException e) {e.printstacktrace ();}   Saxreader reader = new Saxreader (); try {Document document = Reader.read (in); Read XmlElement root = Document.getrootelement (); list<element> beans = root.elements ();//Gets all the <bean>for in the XML (Element Bean:beans) {bean.element ("bean-class "). GetStringValue (); Gets the full path name of the configured class//<bean-class>com.bwf.test.user</bean-class>//system.out.println (Bean.element (" Bean-class "). GetStringValue ());//The Class object is reflected by the full path name class<?> C = class.forname (Bean.element (" Bean-class "). GetStringValue ()); list<element> properties = bean.element ("init"). Elements ("property");//Gets all the properties inside the Configuration object o = C.newinstance (); Reflection creates an object for (Element property:properties) {//Determines whether the property exists in the class's properties and configures the value for object initialization o = Checkpropertyesxit (Property.attribute ("NA Me "). GetStringValue (), O,c,property.getstringvalue ());} Test (O);//Call testing Method}} catch (Documentexception e) {e.printstacktrace ();}} /** * Determines whether a property exists in the properties of the class and the value configured for object initialization * @param propertyname * @param o * @param c * @param propertyvalue * @return */publi  C Static Object checkpropertyesxit (String propertyname,object o,class<?> c,string propertyvalue) {field[] fields = C.getdeclaredfields (); Boolean isexsit = false;//initialized to not exist for (Field Field:fields) {if (Field.getname (). Equals ( PropertyName)) {//description attribute existsIsexsit = true;//splicing The canonical name of the Set method String Setmethod = "Set" +string.valueof (Field.getname (). CharAt (0)). toUpperCase () + Field.getname (). substring (1); try {//Get Set method M = C.getdeclaredmethod (Setmethod, Field.gettype ()); try {// Call the Set method to initialize the value of the property M.invoke (O, New Object[]{propertyvalue});} catch (Illegalaccessexception e) {e.printstacktrace ();} catch (IllegalArgumentException e) {e.printstacktrace ();} catch (InvocationTargetException e) {e.printstacktrace ();}} catch (Nosuchmethodexception e) {e.printstacktrace ();} catch (SecurityException e) {e.printstacktrace ()}}} if (isexsit) {//system.out.println (propertyname+ "exists");} Else{//system.out.println (propertyname+ "does not exist"), try {throw new Nosuchfieldexception (PropertyName + "property does not exist");} catch ( Nosuchfieldexception e) {e.printstacktrace ();}} return o;} /** * Test whether the object has been initialized * @param o */public static void Test (object o) {if (o instanceof user) {User user = (user) O; System.out.println (User.getusername ()); System.out.println (User.getuserpwd ()); System.out.println (User.getuseRAge ()); System.out.println ("----------------");} else if (o instanceof Student) {Student s = (Student) o; System.out.println (S.getstuno ());}}}

  

Result: configured with two user one Student output two user information and Student information

 

Reflection combines XML simple simulation spring to create beans

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.