Some understanding of reflection technology

Source: Internet
Author: User
Tags access properties

Reflection Technology : It's actually loading a specified class dynamically and getting all the content in that class. The bytecode files are encapsulated into objects and the contents of the bytecode files are encapsulated into objects, making it easier to manipulate those members. Simply put: the reflection technique can dissect a class.

The benefits of reflection: greatly enhance the extensibility of the program.

Basic Steps for Reflection:
1. Get the class object, which is the bytecode file object that gets to the specified name.
2, instantiate the object, get the class's properties, methods, or constructors.
3. Access properties, call methods, call constructors to create objects.

There are three ways to get this class object:
1: Obtained through the method getclass that each object has. Cons: You must create the class object before you can call the GetClass method.
2: Each data type (basic data type and reference data type) has a static property class. Cons: This class must be identified first.
The first two methods are not conducive to the extension of the program, because it is necessary to use a specific class to complete the program.
3: The method used in class, the static Forname method.
Specifies what class name to get what class bytecode file object, this way is strongest, as long as the class name of the string passed in.
1. obtained for class loading based on the given class name
String classname = "Cn.itcast.reflect.Person";//From configuration file
Class clazz = class.forname (classname);//This object represents Person.class
2. If you get the object, don't know what type is used to get the object type
Object obj = new person ();
Class clazz1 = Obj.getclass ();//Get the object specific type
3. If you are explicitly getting a class object that is used primarily to pass a reference
Class clazz2 = Person.class;

Use of Reflection:
1), need to get the various components of the Java class, first need to obtain the class object, to obtain the classes object three ways:
Class.forName (classname) for class loading
Obj.getclass () to get the type of the object
Class name. class is used to obtain the specified type,

2), the member method of the Reflection class:
Class clazz = Person.class;
method = Clazz.getmethod (MethodName, New CLASS[]{PARAMCLAZZ1, paramClazz2});
Method.invoke ();

3), the constructor of the Reflection class:
Constructor con = clazz.getconstructor (new class[]{paramclazz1, PARAMCLAZZ2,...})
Con.newinstance (params ...)

4), the properties of the Reflection class:
Field field = Clazz.getfield (FieldName);
Field.setaccessible (TRUE);
Field.setobject (value);

After you get the bytecode file object, you eventually need to create an object of the specified class:
There are two ways to create an object (which is actually how the object is initialized when it is instantiated):
1, call the constructor of the empty argument: the Newinstance () method in the class is used.
2, call the constructor with parameters: first to get the constructor object for the specified argument list, and then initialize the object through the newinstance (actual argument) of the object of the constructor.

In summary, the second way, you must first clear the specific parameters of the constructor type, not easy to expand. So in general, a class that is reflected, the interior usually provides a constructor for a public null argument.

    // 如何生成获取到字节码文件对象的实例对象。        Class clazz = Class.forName("cn.itcast.bean.Person");// 直接获得指定的类型        clazz = Person.class;        // 根据对象获得类型        Objectnew Person("zhangsan"19);        clazz = obj.getClass();
    Object obj = clazz.newInstance();//该实例化对象的方法调用就是指定类中的空参数构造函数,给创建对象进行初始化。当指定类中没有空参数构造函数时,该如何创建该类对象呢?请看method_2();
 Public Static void method_2() throws Exception {Class clazz = Class.forName ("Cn.itcast.bean.Person");//Since there is no constructor for empty arguments in the class, only the constructor that gets the specified argument is instantiated with the function.         //Gets a constructor with parameters. Constructor Constructor = Clazz.getconstructor (String.class,int. Class);//Want to initialize the object, use the constructor's method newinstance ();Object obj = constructor.newinstance ("Zhagnsan", -);//Get all constructors. Constructor[] Constructors = clazz.getconstructors ();//contains only publicconstructors = Clazz.getdeclaredconstructors ();//contains a private         for(Constructor con:constructors) {System. out. println (Con); }    }

Reflect methods in the specified class:
Gets all the methods in the class.
public static void Method_1 () throws Exception {
Class clazz = Class.forName ("Cn.itcast.bean.Person");
Method[] methods = Clazz.getmethods ();//Gets the public method in the class and the public method in the parent class.
Methods = Clazz.getdeclaredmethods ();//Gets the methods in this class, including private methods.
for (Method method:methods) {
System.out.println (method);
}
}

    //Get the specified method;     Public Static void method_2()throwsException {Class clazz = Class.forName ("Cn.itcast.bean.Person");//Gets the method of the specified name. method = Clazz.getmethod ("Show",int. Class,string.class);//Want to run the specified method, of course, the method object is the clearest, in order to let the method run, call the method object's Invoke method, but the method must be run to explicitly belong to the object and the concrete actual parameters. Object obj = clazz.newinstance (); Method.invoke (obj, the,"Hehehe");//Execute a method}//Want to run a private method.      Public Static void Method_3()throwsException {Class clazz = Class.forName ("Cn.itcast.bean.Person");//Want to get private methods. Must use Getdeclearmethod ();method = Clazz.getdeclaredmethod ("Method",NULL);//Private methods cannot be accessed directly because of insufficient permissions. Not to be accessed, can be done by means of violence. Method.setaccessible (true);//generally seldom used, because the private is hidden, so try not to access. }//Reflection static method.      Public Static void Method_4()throwsException {Class clazz = Class.forName ("Cn.itcast.bean.Person"); method = Clazz.getmethod ("function",NULL); Method.invoke (NULL,NULL); }

Some understanding of reflection technology

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.