Java reflection mechanism and Method.invoke detailed _java

Source: Internet
Author: User

Java Reflection mechanism

The Java reflection mechanism is in the running state, and for any class, all the properties and methods of the class are known, and any one of its methods can be invoked for any object, and this dynamically acquired information and the function of the method that dynamically invokes the object are called the reflection mechanism of the Java language.

The Java reflection mechanism mainly provides the following features: To determine at run time the class to which any object belongs, to construct an object of any class at run time, to determine the member variables and methods of any class 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

Copy Code code as follows:

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 attributes of a class declaration through class.

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

2. Get a static property of a class

Copy Code code as follows:

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 gets the class of this category.

Field field = Ownerclass.getfield (fieldName): As above, gets the property declared by class.

Object property = Field.get (Ownerclass): This is somewhat different from the above, because the attribute is static, so take it directly from class.

3. Methods of executing an object

Copy Code code as follows:

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 method = Ownerclass.getmethod (Methodname,argsclass);

Return Method.invoke (owner, args);
}

Class Owner_class = Owner.getclass (): First, you must get the class of this object.

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 by means of the MethodName and the Argsclass of the parameters (a collection of parameter types in the method).

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

4. Perform a static method of a class

Copy Code code as follows:

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 method = Ownerclass.getmethod (Methodname,argsclass);

return Method.invoke (null, args);
}

The basic principle is the same as the example 3, and the difference is the last line, one of Invoke's arguments is NULL, because this is a static method and does not need to run with an instance.

5. New instance

Copy Code code as follows:

Public Object newinstance (String className, object[] args) throws Exception {
Class Newoneclass = Class.forName (className);

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 here is to execute a constructor with a parameter to create a new instance of the method. If you do not need parameters, you can use Newoneclass.newinstance () directly to implement it.

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

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

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

Cons.newinstance (args): Creates a new instance.

6. Deciding whether to be an instance of a class

Copy Code code as follows:

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

7. Get an element in the array

Copy Code code as follows:

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

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.