Java Reflection case

Source: Internet
Author: User

Java Reflection Classic Instance 2007-08-29 17:55:25

Category: Java

Java provides a set of mechanisms for dynamic execution of methods and construction methods, as well as array manipulation, which is called-reflection. The reflection mechanism is the basis of many popular frameworks today, including spring, Hibernate, and so on. The problem of the original reason is not the focus of this article, then let us learn this wonderful mechanism in the example.

1. Get the properties of an object

1 public Object GetProperty (object owner, String fieldName) throws Exception {
2 Class Ownerclass = Owner.getclass ();
3
4 Field field = Ownerclass.getfield (FieldName);
5
6 Object property = Field.get (owner);
7
8 return property;
9}
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

1 Public Object Getstaticproperty (string className, String fieldName)
2 throws Exception {
3 Class Ownerclass = Class.forName (className);
4
5 Field field = Ownerclass.getfield (FieldName);
6
7 Object property = Field.get (Ownerclass);
8
9 return property;
10}

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

1 public Object InvokeMethod (object owner, String methodName, object[] args) throws Exception {
2
3 Class Ownerclass = Owner.getclass ();
4
5 class[] Argsclass = new Class[args.length];
6
7 for (int i = 0, j = args.length; I < J; i++) {
8 Argsclass[i] = Args[i].getclass ();
9}
10
method = Ownerclass.getmethod (MethodName, Argsclass);
12
Return Method.invoke (owner, args);
14}
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 = Ownerclass.getmethod (MethodName, Argsclass): Gets the method to execute by using the class array of method name and parameter.

Method.invoke (owner, args): The argument that executes the Method,invoke method is the object that executes the method, and an array of arguments. The return value is object and is both the return value of the method.


4. Executing a static method of a class

1 Public Object Invokestaticmethod (string className, String methodName,
2 object[] args) throws Exception {
3 Class Ownerclass = Class.forName (className);
4
5 class[] Argsclass = new Class[args.length];
6
7 for (int i = 0, j = args.length; I < J; i++) {
8 Argsclass[i] = Args[i].getclass ();
9}
10
method = Ownerclass.getmethod (MethodName, Argsclass);
12
return Method.invoke (null, args);
14}

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
1
2 public Object newinstance (String className, object[] args) throws Exception {
3 Class Newoneclass = Class.forName (className);
4
5 class[] Argsclass = new Class[args.length];
6
7 for (int i = 0, j = args.length; I < J; i++) {
8 Argsclass[i] = Args[i].getclass ();
9}
10
One Constructor cons = Newoneclass.getconstructor (Argsclass);
12
Return cons.newinstance (args);
14
15}

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

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


7. Get an element in the array
1 public Object Getbyarray (object array, int index) {
2 return Array.get (Array,index);
3}


Complete source code is attached:

Import Java.lang.reflect.Array;
Import Java.lang.reflect.Constructor;
Import Java.lang.reflect.Field;
Import Java.lang.reflect.Method;


/**
* Java Reflection Cookbook
*
* @author Michael Lee
* @since 2006-8-23
* @version 0.1a
*/

public class Reflection {
/**
* Get the public properties of an object
*
* @param owner, FieldName
* @return The Property object
* @throws Exception
*
*/
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;
}

/**
* Get static public properties of a class
*
* @param className class name
* @param fieldName Property name
* @return The Property object
* @throws Exception
*/
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;
}


/**
* Execute an Object method
*
* @param owner
* Object
* @param methodName
* Method Name
* @param args
* Parameters
* @return Method return value
* @throws Exception
*/
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);
}


/**
* Perform a static method of a class
*
* @param className
* Class Name
* @param methodName
* Method Name
* @param args
* Parameter array
* Results returned by @return execution method
* @throws Exception
*/
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);
}



/**
* New instance
*
* @param className
* Class Name
* @param args
* Parameters of constructor function
* @return A new instance
* @throws Exception
*/
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);

}



/**
* is not an instance of a class
* @param obj instance
* @param CLS Class
* @return If obj is an instance of this class, returns True
*/
public boolean isinstance (Object obj, Class cls) {
return cls.isinstance (obj);
}

/**
* Get an element in the array
* @param array arrays
* @param index
* @return Returns the value of the index component in the specified Array object
*/
public object Getbyarray (object array, int index) {
Return Array.get (Array,index);
}
}

Java Reflection case

Related Article

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.