Java Reflection (Reflection)

Source: Internet
Author: User

Basic Concepts

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:

1. At run time, determine the class to which any one object belongs.

2. constructs an object of any class at run time .

3. At run time, judge the member variables and methods that any one class has.

4. A method that invokes any object at run time .

5. set the property value of any one 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 given class with a known name through the reflection APIs at runtime.

Includes its modifiers(such as public, static, and so on), superclass(such as Object), interfaces implemented (such as Serializable), It also includes all information about its constuctors,fields and methods , and can change the fields content or Invoke methods at run time.

Dynamic language

Dynamic language definition "When a program is run, it allows you 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. The meaning of this word is: reflection, Image, reflection , used in Java refers to we can at runtime loading, detection, using the classes is completely unknown during compilation.

In other words, a Java program can load a runtime to know the name of the class, learn its full construct ( but not including the methods definition ), and generate its object entity, or its fields set value, 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.

Introduction to the Java Reflection API

In the JDK, the Java reflection mechanism is implemented primarily by the following classes (except the first one) in the java.lang.reflect Package

   class: Represents a class that is located under the Java.lang package.

   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.

Class object

To use reflection, you first need to get the class object corresponding to the classes you want to manipulate.

Java , regardless of how many objects of a class are generated, these objects will correspond to the same class object.

This class object is by the JVM generated, through which it is able to learn the structure of the entire class.

commonly used to get class 3 of Objects type of method:

  1. use the static method of class . For example:

Class.forName ("java.lang.String");

  2.use the. class syntax for the classes . such as:

String.class;

  3. Use the GetClass () method of the object . Such as:

String str = "AA"; class<?> classType1 = Str.getclass ();

The GetClass () method is defined in the object class, is not a static method, needs to be called through an object, and it is declared final, indicating that it cannot be overridden by a quilt class.

The class object ClassType obtained by direct print outputs:

Class full category name

If the GetName () method of the class object is called, the full class name is output and class is not added.

Routine 1: Getting methods

The routine Dumpmethods class demonstrates the basic role of the reflection API, which reads the class name specified by the command-line arguments, and then prints the method information that the class has.

Import Java.lang.reflect.method;public class dumpmethods{public    static void Main (string[] args) throws Exception// Add this sentence after the method, and the exception disappears    {        //Get the class object that is identified by the string        class<?> ClassType = Class.forName ("java.lang.String"); /Here the string to specify the class name, so the parameter gets can be a run-time behavior, you can use Args[0]                //Return class object corresponding to the classes or interfaces, the declared array of all methods (including private methods)        method[] methods = Classtype.getdeclaredmethods ();                Traverse output All method declaration for        (method Method:methods)        {            System.out.println (method);        }    }}

Routine 2: Calling a method by reflection

The method is called through reflection. See Code and notes for details:

Import Java.lang.reflect.method;public class invoketester{public int Add (int param1, int param2) {return PA    Ram1 + param2;    public string Echo (String message) {return "Hello:" + message; } public static void Main (string[] args) throws Exception {//previous normal execution means invoketester tester = new INV        Oketester ();        System.out.println (Tester.add (1, 2));        System.out.println (Tester.echo ("Tom"));        System.out.println ("---------------------------");  By the way of reflection///First step, Get class object//Before using the method is: Class.forName () method gets//here with the second method, class name. class<?>        ClassType = Invoketester.class;        To generate a new object: Use the Newinstance () method Object invoketester = Classtype.newinstance (); System.out.println (Invoketester instanceof Invoketester); Output true//By reflection call Method//First need to get the method object corresponding to the methods Addmethod = Classtype.getmethod ("Add", New Clas S[] {Int.class, int.class}); The first parameter is the method name, and the second parameter is an array of the class objects required by this method//Call the target method Object result = Addmethod.invoke (Invoketester, new object        [] {1, 2}); SYSTEM.OUT.PRINTLN (result); At this point, result is an integer type//Call to the second method Echomethod = Classtype.getdeclaredmethod ("echo", new class[]{        String.class});        Object result2 = Echomethod.invoke (invoketester, New object[]{"Tom"});    System.out.println (RESULT2); }}

Build Object

  To build an object by using the class's constructor without parameters, we have two ways:

1. Obtain the class object first, and then generate it directly from the Newinstance () method of the Class object:

     class<?> ClassType = String.class;     Object obj = classtype.newinstance ();

2. Obtain the class object first, then obtain the corresponding constructor object through the object, and then through the constructor object's Newinstance () method to generate

(where customer is a custom class with a parameterless constructor and a constructor with parameters):

    class<?> ClassType = Customer.class;    Gets the Constructor object, where    Constructor cons = Classtype.getconstructor (new class[] {}) is obtained for the first parameterless construction method;    Construct a method to generate an object    obj = cons.newinstance (new object[] {});

  If you want to build an object from a class's constructor with parameters, you can only use one of the following methods:

(Customer is a custom class with a constructor with no arguments, and a constructor with parameters, passing in strings and integers)

    class<?> ClassType = Customer.class;    Constructor cons2 = Classtype.getconstructor (new class[] {string.class, Int.class});    Object obj2 = cons2.newinstance (new object[] {"Zhangsan", 20});

You can see that calling the constructor method to build the object is similar to calling a generic method, unlike getting a constructor object from a class object without specifying a name and specifying a name when getting the method object.

Go to http://www.cnblogs.com/mengdd/archive/2013/01/26/2877972.html with the original

Java Reflection (Reflection)

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.