The sample code is as follows:
Reflecttest class:
Import Java.lang.reflect.Constructor;
Import Java.lang.reflect.Method;
public class Reflecttest {
public static car Initbydefaultconst () throws Throwable
{
1. Get car class object through class loader
ClassLoader loader = Thread.CurrentThread (). Getcontextclassloader ();
Class clazz = Loader.loadclass ("Com.jike.spring.chapter03.reflect.Car");
2. Get the default constructor object for the class and instantiate the car
Constructor cons = Clazz.getdeclaredconstructor ((class[)) null);
Car car = (car) cons.newinstance ();
3. Setting properties by Reflection method
Method Setbrand = Clazz.getmethod ("Setbrand", String.class);
Setbrand.invoke (Car, "Mercedes");
Method SetColor = Clazz.getmethod ("SetColor", String.class);
Setcolor.invoke (Car, "black");
Method setmaxspeed = Clazz.getmethod ("Setmaxspeed", Int.class);
Setmaxspeed.invoke (car,200);
return car;
}
public static car Initbyparamconst () throws throwable{
1. Get car class object through class loader
ClassLoader loader = Thread.CurrentThread (). Getcontextclassloader ();
Class clazz = Loader.loadclass ("Com.jike.spring.chapter03.reflect.Car");
2. Gets the constructor object with parameters for the class
Constructor cons = Clazz.getdeclaredconstructor (new Class[]{string.class,string.class,int.class});
3. Instantiate the car with the constructor object of the parameter
Car car = (car) cons.newinstance (new object[]{"BMW", "Red", 180});
return car;
}
public static void Main (string[] args) throws Throwable {
Car car1 = Initbydefaultconst ();
Car car2 = Initbyparamconst ();
Car1.introduce ();
Car2.introduce ();
}
}
Car class:
public class Car {
Private String brand;
private String color;
private int maxspeed;
1. Default constructor
Public car () {
System.out.println ("Init car!!");
}
2. With parameter constructor
Public car (String brand,string color,int maxspeed) {
This.brand = brand;
This.color = color;
This.maxspeed = Maxspeed;
}
3. Methods with no parameters
public void introduce () {
System.out.println ("Brand: +brand+"; color: "+color+"; Maxspeed: "+maxspeed");
}
Public String Getbrand () {
return brand;
}
public void Setbrand (String brand) {
This.brand = brand;
}
Public String GetColor () {
return color;
}
public void SetColor (String color) {
This.color = color;
}
public int getmaxspeed () {
return maxspeed;
}
public void setmaxspeed (int maxspeed) {
This.maxspeed = Maxspeed;
}
}
-------------------------------------------------------------------------
Import Java.io.InputStream;
Import Java.lang.reflect.Method;
Import Java.util.HashMap;
Import Java.util.Iterator;
Import Java.util.Map;
Import Org.dom4j.Attribute;
Import org.dom4j.Document;
Import org.dom4j.Element;
Import Org.dom4j.io.SAXReader;
public class Beanfactory {
Private map<string, object> beanmap = new hashmap<string, object> ();
/**
* Initialization of the Bean factory.
*
* @param XML XML configuration file
*/
public void init (String xml) {
try {
1. Create a Reader object to read the configuration file
Saxreader reader = new Saxreader ();
2. Gets the class loader object in the current thread
ClassLoader ClassLoader = Thread.CurrentThread (). Getcontextclassloader ();
3. Get the specified XML file from the class directory
InputStream ins = Classloader.getresourceasstream (XML);
Document doc = reader.read (INS);
Element root = Doc.getrootelement ();
Element foo;
4. Traverse the bean instance in the XML file
for (Iterator i = root.elementiterator ("Bean"); I.hasnext ();) {
Foo = (Element) i.next ();
5. For each bean instance, get the Bean's property ID and Class
Attribute id = foo.attribute ("id");
Attribute cls = Foo.attribute ("class");
6. Use Java reflection mechanism to get class object by name of class
Class bean = Class.forName (Cls.gettext ());
7. Get the information for the corresponding class
Java.beans.BeanInfo info = java.beans.Introspector.getBeanInfo (bean);
8. Get a description of its properties
Java.beans.PropertyDescriptor pd[] = info.getpropertydescriptors ();
9. Create an object and assign a value to the object's properties in the following code
Object obj = bean.newinstance ();
10. Iterate through the Bean's property properties
for (Iterator ite = Foo.elementiterator ("property"); Ite.hasnext ();) {
Element Foo2 = (Element) Ite.next ();
11. Get the property's name attribute
Attribute name = Foo2.attribute ("name");
String value = null;
12. Gets the value of the child element value of the property
for (Iterator ite1 = Foo2.elementiterator ("value"); Ite1.hasnext ();)
{
element node = (element) Ite1.next ();
Value = Node.gettext ();
Break
}
13. Invoke a set method of the object using the Java reflection mechanism and set the value in
for (int k = 0; k < pd.length; k++) {
if (Pd[k].getname (). Equalsignorecase (Name.gettext ()))
{
Method mset = null;
Mset = Pd[k].getwritemethod ();
Mset.invoke (obj, value);
}
}
}
14. Put the object into the Beanmap, where key is the ID value, value is the object
Beanmap.put (Id.gettext (), obj);
}
catch (Exception e) {
System.out.println (E.tostring ());
}
}
/**
* Get the Bean's object through the bean's ID.
*
* @param beanname
* The ID of the bean
* @return return the corresponding object
*/
Public Object Getbean (String beanname) {
Object obj = Beanmap.get (beanname);
return obj;
}
/**
* Test method.
*
* @param args
*/
public static void Main (string[] args) {
Beanfactory factory = new Beanfactory ();
Factory.init ("Conf/config.xml");
JavaBean JavaBean = (JavaBean) factory.getbean ("JavaBean");
System.out.println ("username=" + javabean.getusername ());
System.out.println ("password=" + Javabean.getpassword ());
}
}