A detailed explanation of the Java reflection mechanism and Method.invoke interpretation GetMethod

Source: Internet
Author: User

Java Reflection mechanism

The Java reflection mechanism is in the running state, for any class, can know all the properties and methods of this class, for any one object, can call any of its methods; This dynamically acquired information and the ability to dynamically invoke the method of the object is called the reflection mechanism of the Java language.
The Java Reflection mechanism provides the following functions: To determine the class to which any object belongs at run time, to construct an object of any class at run time, to determine the member variables and methods that any class has at run time, to invoke a method of any object at run time, and to generate a dynamic proxy.
1. Get the properties of an object

public object GetProperty (object owner, String fieldName) throws Exception {        Class ownerclass = Owner.getclass (); 
   
    field Field = Ownerclass.getfield (fieldName);        Object property = Field.get (owner);        return property;   }  
   

Class Ownerclass = Owner.getclass (): Gets the class of the object.

Field field = Ownerclass.getfield (FieldName): Gets the properties of the class declaration through class.

object property = Field.get (owner): an instance of the attribute is obtained from the object, and if the property is non-public, the Illegalaccessexception is reported here.

2. Get static properties for a class

Public Object Getstaticproperty (string className, String fieldName)                throws Exception {        Class ownerclass = Class.forName (className);        Field field = Ownerclass.getfield (fieldName);        Object property = Field.get (Ownerclass);        return property;   }  

Class Ownerclass = Class.forName (className): First, the class is given.

Field field = Ownerclass.getfield (fieldName): As above, the properties of the class declaration are obtained by class.

Object property = Field.get (Ownerclass): Here is a bit different from the above because it is static, so it is taken directly from class.

3. Methods for executing an object

public object InvokeMethod (object owner, String methodName, object[] args) throws Exception {        Class ownerclass = Owner . GetClass ();        class[] Argsclass = new Class[args.length];        for (int i = 0, j = args.length; I < J; i++) {            Argsclass[i] = Args[i].getclass ();        }         method = Ownerclass.getmethod (Methodname,argsclass);        Return Method.invoke (owner, args);   }

Class Owner_class = Owner.getclass (): The object's class must be obtained first.

5~9: A class array of configuration parameters, as a condition for finding method.

Method method = Ownerclass.getmethod (MethodName, Argsclass): Gets the method to execute through an array of methodName and the argsclass of the arguments (the collection of parameter types in the method).

Method.invoke (owner, args): The parameter that executes the Method.invoke method is the object that executes the method, the owner, and the parameter array args, which can be understood as follows: The methods method with the parameter args in the owner object. The return value is object and is both the return value of the method.

4. Executing a static method of a class

Public Object Invokestaticmethod (string className, String methodName,                object[] args) throws Exception {        Class Ownerclass = Class.forName (className);        class[] Argsclass = new Class[args.length];        for (int i = 0, j = args.length; I < J; i++) {            Argsclass[i] = Args[i].getclass ();        }       method = Ownerclass.getmethod (Methodname,argsclass);        return Method.invoke (null, args);    }  

The basic principle is the same as example 3, the difference is the last line, and an argument to invoke is NULL, because this is a static method and does not need to be run with an instance.

5. Create a new instance

Public Object newinstance (String className, object[] args) throws Exception {        class Newoneclass = Class.forName (class Name);        class[] Argsclass = new Class[args.length];        for (int i = 0, j = args.length; I < J; i++) {            Argsclass[i] = Args[i].getclass ();        }        Constructor cons = Newoneclass.getconstructor (argsclass);        Return cons.newinstance (args);     

The method used here is to execute a constructor with parameters to create a new instance of the method. If no parameters are required, it can be implemented directly using Newoneclass.newinstance ().

Class Newoneclass = Class.forName (className): The first step is to get the Class of the instance to be constructed.

5~ Line 9th: Gets the class array of the arguments.

Constructor cons = Newoneclass.getconstructor (Argsclass): Gets the constructor.

Cons.newinstance (args): new instance.

6. Determine if an instance of a class

public boolean isinstance (Object obj, Class cls) {        return cls.isinstance (obj);   }  

7. Get an element in the array

public object Getbyarray (object array, int index) {        return array.get (Array,index);   }  

A detailed explanation of the Java reflection mechanism and Method.invoke interpretation GetMethod

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.