Java Reflection Mechanism Learning

Source: Internet
Author: User

Java reflection is a very important feature of the Java language, which makes Java concrete "dynamic".

In the Java Runtime environment, for any class, can you know what the properties and methods of this class are? Can any one of its methods be called for any of the objects? The answer is yes. This dynamic acquisition of information for classes and the ability to dynamically invoke objects is derived from the Java language's reflection (Reflection) mechanism.

The Java reflection mechanism mainly provides the following features:

    • Determine the class to which any object belongs at run time.
    • Constructs an object of any class at run time.
    • At run time, determine the member variables and methods that any one class has.
    • A method that invokes any object at run time.

Reflection is a key property of Java as a dynamic (or quasi-dynamic) language. This mechanism allows the program to obtain the internal information of any known name class, including its modifiers (such as public, static, and so on), superclass (such as Object), through the reflection APIs at runtime. The implementation of interfaces (for example, serializable) also includes all the information of fields and methods, and can change the fields content or Invoke methods at run time.

In general, the developer community speaks of dynamic language, which is broadly agreed to as a definition: "When a program is run, it is allowed to change the program structure or variable type, which is called Dynamic language." From this point of view, Perl,python,ruby is a dynamic language, and c++,java,c# is not a dynamic language.

Although Java is not a dynamic language under such definitions and classifications, it has a very prominent dynamic correlation mechanism: Reflection. This word means "reflection, image, reflection," which is used in Java to refer to the classes that we can load, detect, and use completely unknown during compilation. In other words, a Java program can load a runtime to know the name of a class, learn its full construct (but not including the methods definition), and generate its object entities, or set values on its fields, or evoke its methods. This ability to "See Through Class" (the ability of the program to examine itself) is called introspection (introspection, vipassana, introspection). Reflection and introspection are the two terms that are often and are mentioned.

In the JDK, the Java reflection mechanism is implemented primarily by the following classes, which are located in the Java.lang.reflect package:

    • Class: Represents a Class.
    • Field class: Represents a member variable of a class (a member variable is also called a property of a class).
    • Method class: Methods that represent classes.
    • Constructor class: Represents the construction method of a class.
    • Array class: Provides a static method for dynamically creating an array, and for accessing the elements of an array.

Here are a few examples to look at the practical use of the Reflection API:

1. Get the properties of an object
PublicObjectGetProperty(ObjectOwner,string fieldname) throws  Exception {class ownerclass =  Owner. (); field field = ownerclass.getfield (fieldnameobject property = field.get (ownerreturn property               /span>                

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
PublicObjectGetstaticproperty(StringClassName,StringFieldName) throws exception {class ownerclass = class. Forname (classnamefield field = ownerclass.getfield (fieldnameobject property = field.get (ownerclassreturn property               /span>                

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
PublicObjectInvokeMethod(ObjectOwner,StringMethodName,Object[]Args)ThrowsException{ClassOwnerclass=Owner.GetClass();Class[]Argsclass=NewClass[Args.Length];For(IntI=0,J=Args.Length;I<J;i++) {argsclass [i] = args[i< Span class= "P" >. getclass (); } method method = ownerclass< Span class= "P". getmethod (methodname, Argsclass); return method. Invoke (ownerargs               /span>                

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
PublicObjectInvokestaticmethod(StringClassName,StringMethodName,Object[]Args)ThrowsException{ClassOwnerclass=Class.Forname(ClassName);Class[]Argsclass=NewClass[Args.Length];For(IntI=0,J=Args.Length;I<J;i++) {argsclass [i] = args[i< Span class= "P" >. getclass (); } method method = ownerclass< Span class= "P". getmethod (methodname, Argsclass); return method. Invoke (nullargs               /span>                

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
PublicObjectNewinstance(StringClassName,Object[]Args)ThrowsException{ClassNewoneclass=Class.Forname(ClassName);Class[]Argsclass=NewClass[Args.Length];For(IntI=0,J=Args.Length;i < ji++) {argsclass [i] = args[i< Span class= "P" >. getclass (); } constructor cons = newoneclass< Span class= "P". getconstructor (argsclassreturn cons. Newinstance (args               /span>                 

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); }

Java Reflection Mechanism Learning

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.