Java Reflection mechanism

Source: Internet
Author: User
Tags gettext reflection throwable

Java Reflection mechanism

The Java language allows programmatic indirect manipulation of class object instances, where class files are loaded by the ClassLoader, and a meta-information object that describes the class structure is formed in the JVM, where the structure information of the class is learned by the meta-information object. The source information object can be used to learn the structure information of class, such as constructors, properties and methods, etc.

Give a small example of reflection:

The car class consists of three attributes, and an parameterless constructor and a parameter constructor

 Public classCar {PrivateString brand; PrivateString color; Private intmaxspeed;  PublicCar () {System.out.println ("Init Car"); }   PublicCar (string brand, String color,intmaxspeed) {     This. Brand =brand;  This. color =color;  This. Maxspeed =maxspeed; }     Public voidintroduce () {System.out.println ("Brand:" +brand+ "color:" +color+ "Max speed:" +maxspeed); }   PublicString Getbrand () {returnbrand; }   Public voidSetbrand (String brand) { This. Brand =brand; }   PublicString GetColor () {returncolor; }   Public voidsetcolor (String color) { This. color =color; }   Public intgetmaxspeed () {returnmaxspeed; }   Public voidSetmaxspeed (intmaxspeed) {     This. Maxspeed =maxspeed; }}

Here, the object is instantiated using the reflection get constructor

 Public classReflecttest {//To initialize a car object by default construction method   Public StaticCar Initdefaultconst ()throwsthrowable{//1. Get the car class object through the class loaderClassLoader loader =Thread.CurrentThread (). Getcontextclassloader (); Class Clazz=loader.loadclass ("Com.xiongda.spring.reflect.Car"); //2. Gets the default constructor object for the class and instantiates carConstructor Cons =clazz.getdeclaredconstructor (NULL); Car Car=(Car) cons.newinstance (); //3. Setting properties by Reflection methodMethod Setbrand =clazz.getmethod ("Setbrand", String.class); Setbrand.invoke (Car,Benz); Method SetColor=clazz.getmethod ("SetColor", String.class); Setcolor.invoke (Car,Black); Method Setmaxspeed=clazz.getmethod ("Setmaxspeed",int.class); Setmaxspeed.invoke (Car,200); returncar; }  //initializing a Car object with a parameter construction method   Public StaticCar Initparamconst ()throwsthrowable{//1. Get the car class object through the class loaderClassLoader loader =Thread.CurrentThread (). Getcontextclassloader (); Class Clazz=loader.loadclass ("Com.xiongda.spring.reflect.Car"); //2. Gets the parameter constructor object for the class and instantiates carConstructor cons =clazz.getdeclaredconstructor (String.class, String.class,int.class); Car Car= (Car) cons.newinstance ("BMW", "Red", 180); returncar; }       Public Static voidMain (string[] args)throwsthrowable {Car car1=Reflecttest.initdefaultconst (); Car car2=Reflecttest.initparamconst ();    Car1.introduce ();  Car2.introduce (); }}

In traditional methods, we typically set properties using a constructor or set method.

Class loader ClassLoader
The class loader is looking for the class bytecode file and constructs the object component represented by the class within the JVM, which is mainly responsible for ClassLoader and its subclasses, and ClassLoader is an important Java Runtime system component that is responsible for locating and loading class bytecode files at run time.

Working mechanism:
1. Loading: Finding and Importing class files
2. Link: Perform validation, preparation and resolution steps
3. Initialization: Initialization of static variables and static blocks of code for a class

Important methods:
1.Class loadclass (String name)
2.Class defineclass (String name,byte[] B, int off, int len)
3.Class Findsystemclass (String name)
4.Class Findloadedclass (String name)
5.ClassLoader getParent ()

Class reflection objects describe the semantic structure of classes, and you can get the reflection objects of the class elements, such as constructors, member variables, methods, and so on, and programmatically manipulate the target objects through these reflective objects. These reflective object classes are defined in the Java.reflect package

The three most important reflection classes:
Constructor
Method
Field

In spring, the implementation class, parameter information, and so on, can be configured in its corresponding configuration file, so when the implementation class or parameter information needs to be changed, only the configuration file needs to be modified, and we can also inject the other objects that its object needs, which are done in the configuration file

Spring's IOC implementation principle uses the Java reflection mechanism, the spring factory class will help us to complete the configuration file reading, uses the reflection mechanism to inject the object and so on, we can obtain the corresponding object through the bean name

The basic JavaBean

 Public classJavaBean {PrivateString username; PrivateString password;  PublicString GetUserName () {returnusername; }   Public voidSetusername (String username) { This. Username =username; }   PublicString GetPassword () {returnpassword; }   Public voidSetPassword (String password) { This. Password =password; }  }

Read the configuration file and instantiate the JavaBean through the Java reflection mechanism

 Public classBeanfactory {Privatemap<string, object> beanmap =NewHashmap<>(); /*** Initialization of the Bean factory *@paramXML*/   Public voidInit (String sxml) {InputStream ins=NULL; Document Doc=NULL; Try {        //1. Create a Reader object to read the configuration fileSaxreader reader =NewSaxreader (); //2. Get the class loader object in the current threadClassLoader ClassLoader =Thread.CurrentThread (). Getcontextclassloader (); //3. Get the specified XML file from the class directoryINS =Classloader.getresourceasstream (sxml); if(INS = =NULL) {System.out.println ("Get Stream failed"); } Doc=reader.read (INS); Element Root=doc.getrootelement ();                Element foo; //4. Traversing a bean instance in an XML file         for(Iterator i =root.elementiterator ("Bean"); I.hasnext ();) {foo=(Element) i.next (); //5. For each bean instance, get the Bean's attribute ID and classAttribute ID =foo.attribute ("id"); Attribute CLS=foo.attribute ("Class"); //6. Use the Java reflection mechanism to get the class object through the name of ClassClass Bean =Class.forName (Cls.gettext ()); //7. Get the information for the corresponding classJava.beans.BeanInfo info =Java.beans.Introspector.getBeanInfo (Bean); //8. Get a description of its propertiesJava.beans.PropertyDescriptor pd[] =info.getpropertydescriptors (); //9. Create an object and assign a value to the object's properties in the next codeObject obj =bean.newinstance (); //10. Iterate over the property properties of the Bean           for(Iterator ite = Foo.elementiterator ("property")); Ite.hasnext ();) {Element Foo2=(Element) ite.next (); //11. Get the property's name attributeAttribute name = Foo2.attribute ("name"); String value=NULL; //12. Gets the value of the property's child element, value             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 reflection mechanism of Java and set the value in             for(intk=0;k<pd.length;k++){              if(Pd[k].getname (). Equalsignorecase (Name.gettext ())) {Method Mset=NULL; Mset=Pd[k].getwritemethod ();              Mset.invoke (obj, value); }            }          }                    //14. Place the object into the Beanmap, where key is the ID value and value is the objectBeanmap.put (Id.gettext (), obj); }      } Catch(ClassNotFoundException | instantiationexception | illegalaccessexception |illegalargumentexception| InvocationTargetException | documentexception |introspectionexception e) {        //TODO auto-generated Catch block        if(doc = =NULL) {System.out.println ("Get Failed");      } e.printstacktrace (); }   }     PublicObject Getbean (String beanname) {Object obj=Beanmap.get (beanname); returnobj; }     Public Static voidMain (string[] args)throwsthrowable {beanfactory Factory=Newbeanfactory (); Factory.init ("Config +"); JavaBean JavaBean= (JavaBean) factory.getbean ("JavaBean"); System.out.println ("Username" +javabean.getusername ()); System.out.println ("Password" +Javabean.getpassword ()); }}

XML file

<?XML version= "1.0" encoding= "UTF-8"?><Beans>    <BeanID= "JavaBean"class= "Com.xiongda.spring.reflect.JavaBean">        < Propertyname= "username">            <value>Geek College</value>        </ Property>        < Propertyname= "Password">            <value>1234567890</value>        </ Property>    </Bean></Beans>

Note: If you are using Eclipse, this XML file must be placed in the bin directory, otherwise a null pointer exception will be reported. But then I found out that there was no problem with idea. (It took a lot of time to solve this thing, so far it's not clear why this difference exists)

(Note: The use of Saxreader requires guide package dom4j)

Java Reflection mechanism

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.