For a simple simulation of the Spring framework:
a). reading XML configuration file
B.) Using Java reflection mechanism to get objects
Step one: Create an interface, define a method to get the object Getbean ():
Public interface Beanfactory {
public Object Getbean (String name);
}
Step Two: Create a class Xmlcontext to implement the Getbean method in the Beanfactory interface:
public class Xmlcontext implements Beanfactory {//object name plus object instance private map<string, object> beans = new Hashmap<st
Ring, object> ();
Using Jdom to read the XML file to get the object name, to get the object public Xmlcontext () throws Exception {Saxbuilder builder = new Saxbuilder () by reflection;
InputStream file = new FileInputStream ("Test.xml"); Document document = Builder.build (file); Get the object Element root = Document.getrootelement ();//Get the root node List<element> ;
List = Root.getchildren ();
for (Element elements:list) {//Get the property value, which is the object's first name String objectname = elements.getattributevalue ("id");
In getting the path of the class, the class type of the class is fetched through Java reflection, and the object String classpath = Elements.getattributevalue ("class") of the class is obtained;
Object obj = Class.forName (classpath). newinstance ();
Beans.put (objectname, obj);
Gets the property node under the child node list<element> eles = Elements.getchildren ("property");
Traverse for (Element e:eles) {String proname = e.getattributevalue (' name '); Object beanobj = This.getbean (E.getattributevalue ("Bean"));
System.out.println (Beanobj.tostring ()); Then invoke the service's construction method String methodname = "Set" + proname.substring (0, 1). toUpperCase () + proname.substring (
1);
System.out.println ("methodname:" + methodname);
Gets constructed by reflection method methods = Obj.getclass (). GetMethod (methodname, Beanobj.getclass (). getinterfaces () [0]);
Method.invoke (obj, beanobj);
@Override public Object Getbean (String name) {return beans.get (name); }
}