------of the interview question Java reflection mechanism

Source: Internet
Author: User
Tags instance method reflection


I. Overview of the reflection mechanism

The Java reflection mechanism is a running state in which all the properties and methods of this class can be obtained for any class, and any one of its properties and methods can be called for any object. This dynamic access to information at run time and the ability to dynamically invoke objects is called the Java Reflection mechanism.

The class class, together with the Java.lang.reflect class library, supports the concept of reflection, which contains the Field,method,constructor class (each class implements the member interface). These types of objects are created by the JVM at run time to represent the corresponding members in the unknown class.

This allows you to create new objects using constructor, read and modify the fields associated with the Field object with the Get () and set () methods, and invoke the method associated with the methods object with the Invoke () method. In addition, you can call GetFields () GetMethods () and GetConstructors () to return an array of objects that represent fields, methods, and constructors. This way, the information of an anonymous object can be fully determined at run time, and there is no need to know anything at compile time.

Second, the way to get the bytecode

There are three ways to get the bytecode (Class) object of a class in Java

    • With the GetClass () method in the object class, you want to use this method to clarify the specific class and create an object of that class.
    • All data types have a static property. class to get the corresponding class object. However, it is still clear to the class before the static members in the class can be called.
    • The bytecode object of the class can be obtained as long as it is given the string name of the class, which makes it more extensible. Complete with the Class.forName () method, you must specify the fully qualified name of the class, since the first two methods get the bytecode object of the class in the case of knowing the class, so there is no exception, but the Class.forName () method if the path to the wrong class is reported The classnotfoundexception exception.
Package com.jas.reflect;Publicclass Reflecttest { public static void main (string[] args) {Fruit Fruit = new Fruit (); class<?> Class1 = Fruit.getclass (); //Method one class<?> class2 = Fruit.class; //Method two Class CLASS3 = null; try { //method Three, if the package name where the class is not specified is reported classnotfoundexception exception class3 = Class.forName ("Com.jas.reflect.Fruit");} catch (ClassNotFoundException e) {e.printstacktrace ();} System.out.println (Class1 + " " +class2 + "" + Class3);}} Class fruit{}               

Third, through the reflection mechanism to obtain the class information

Creates an object from the reflection mechanism, obtains the object's constructor object before creating the object, and creates an instance of the corresponding class from the constructor object.

The following code creates a non-participating object instance during runtime, respectively. Since the GetConstructor () method throws a lot of exceptions with the Newinstance () method (you can see them through the source code), here's a shorthand for throwing a exception directly below.

Package com.jas.reflect;Import Java.lang.reflect.Constructor;PublicClassreflecttest {public static void main (string[] args) throws Exception {class clazz = null; clazz = Class.forName ( "Com.jas.reflect.Fruit"); Constructor<fruit> Constructor1 = Clazz.getconstructor (); constructor<fruit> Constructor2 = Clazz.getconstructor (String.class); Fruit fruit1 = Constructor1.newinstance (); Fruit fruit2 = constructor2.newinstance ( "Apple");}} Class fruit{public fruit () {System.out.println (" parameterless constructor run ....... "); } public fruit (String type) {System.out.println (" with the parametric constructor run ... "+ type); }}

Output:
no parameter constructor run ......
The parametric constructor run ...... Apple

The properties in class are obtained through the reflection mechanism.

Package com.jas.reflect;Import Java.lang.reflect.Field;PublicClassreflecttest {PublicStaticvoidMain (string[] args)Throws Exception {class<?> clazz =Null Field field =Null Clazz = Class.forName ("Com.jas.reflect.Fruit");field = Clazz.getfield ("num"); The GetField () method cannot get a private propertyfield = Clazz.getfield ("type"); Nosuchfieldexception exception is reported when accessing private fields field = Clazz.getdeclaredfield ( "type"); //gets the private type attribute field.setaccessible (true); //access to private fields is unchecked Fruit Fruit = (Fruit) clazz.newinstance (); //Create an instance of the parameterless object Field.set (Fruit, "Apple"); //assigns a value to the parameterless Object instance Property Object type = Field.get (fruit); //gets the property value fruit (type) through the System.out.println object;}} Class fruit{public int num; private String type; public fruit () {System.out.println ( public fruit (String type) {System.out.println (" with the parametric constructor run ... "+ type); }} 

Output:
no parameter constructor run ......
Apple

Get the method in class and run it through the reflection mechanism.

Package com.jas.reflect;Import Java.lang.reflect.Constructor;Import Java.lang.reflect.Method;PublicClassreflecttest {PublicStaticvoidMain (string[] args)Throws Exception {Class clazz =Null Method method =Null Clazz = Class.forName ("Com.jas.reflect.Fruit"); constructor<fruit> fruitconstructor = Clazz.getconstructor (String.class); Fruit Fruit = fruitconstructor.newinstance ("Apple");Create a Parameter object instance method = Clazz.getmethod ("Show",NULL);Get empty Parameters Show Method Method.invoke (fruit,NULL);Executes the no parameter method = Clazz.getmethod ("Show",Int.class); //Get the Show Method Method.invoke (fruit,20); //Execute a method}} Class fruit{ private String type; public Fruit (String type) { this.type = type;} public void Show () {System.out.println ("Fruit type =" + type);} public void Show (int num) {System.out.println ("Fruit type =" + Type + "...) Fruit num = "+ num";}}                 

Output:
Fruit type = Apple
Fruit type = Apple ..... Fruit num = 20

Iv. Reflection mechanism Simple application (use simple factory to create objects)

Class.forName () produces results that are not known at compile time, so all method signature information is extracted at execution time. The reflection mechanism can create an object that is completely unknown at compile time and invoke the method of the object.

Here is an application of the reflection mechanism and generics that create different types of instances from a factory class.

To create an instance class of an object Apple:

package com.jas.reflect;public interface Fruit {}class Apple implements Fruit{}

Loaded configuration file Config.properties:

 Fruit=com.jas.reflect.Apple

Factory class Basicfactory:

Package com.jas.reflect;Import Java.io.FileReader;Import java.util.Properties;PublicClassbasicfactory {PrivateBasicfactory () {}Privatestatic Basicfactory BF =New Basicfactory ();Privatestatic Properties Pro =Nullstatic{Pro =New Properties ();try{Load the configuration file through the ClassLoader pro.load (New FileReader (BasicFactory.class.getClassLoader (). GetResource ("Config.properties"). GetPath ())); }catch (Exception e) {e.printstacktrace ();}} public static basicfactory getfactory () { return BF;} //Use generics to get Universal object public <T> T newinstance (class<t> clazz) {String cName = Clazz.getsimplename (); c8>//gets the class name of the bytecode object String clmplname = Pro.getproperty (cName); the fully qualified name try{ return (T) Class.forName (clmplname) of the class is obtained from the configuration file according to the class name of the bytecode object. newinstance (); //Create an instance object based on the fully qualified name of the class} catch (Exception e) { throw new RuntimeException (e);       }}} 

To create an object instance:

package com.jas.reflect;public class ReflectTest { public static void main(String[] args) throws Exception { Fruit fruit = BasicFactory.getFactory().newInstance(Fruit.class); System.out.println(fruit); }}

Output
[Email protected]

The above example uses a factory to create instances of different objects, in this way can reduce the coupling degree of code, the code is greatly expanded, the previous to create Apple objects need to create Apple objects through the new keyword, if we also want to create an orange object? It would be cumbersome to create an instance from the New keyword and transform it up to fruit.

Now we have a factory directly, you just configure the information in the configuration file you want to create objects, you can create any type of object you want, is not much simpler? The value of the visible reflection mechanism is astonishing.

The underlying implementation of the IOC in spring is the reflection mechanism, and the spring container will help us create an instance, the method used in the container is reflection, by parsing the XML file, obtaining the contents of the id attribute and class attribute, and using the reflection principle to create an instance object of the class in the configuration file. Into the bean container in spring.

Reference books:
"Java programming thought" Bruce Eckel the translation of Chen Haopeng

------of the interview question 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.