The reflection mechanism of Java

Source: Internet
Author: User

A: Basic concept: In Java runtime, for any class, can you know the corresponding properties and methods of this class? For an object, can you know which methods can call it? 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 .

Second: The Java reflection mechanism mainly provides the following functions:

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.

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.

Three: 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."

Java, however, is not a dynamic language, but Java can also implement a reflection mechanism (in other words, Java programs can load a runtime to know the name of 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. )

Four: Class object:

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

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

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

Three ways to get a class object:

1: Use static methods for class classes:

1 class.forname ("java.lang.String");

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

1 String.class

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

1 " AA " ; 2 class<?> classType1 = Str.getclass ();

Note: 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.

Course 1: Get the Method!

1 import Java.lang.reflect.Method;2 3  Public classDumpmethods4 {5      Public Static voidMain (string[] args) throws Exception//Add this sentence after the method, and the exception disappears.6     {7         //gets the class object for the classes identified by the string8class<?> ClassType = Class.forName ("java.lang.String");//Passing a string here specifies the class name, so the parameter fetch can be a run-time behavior, which can be used args[0]9         Ten         //returns an array of all the methods declared in the class or interface corresponding to the class object (including private methods) OneMethod[] Methods =classtype.getdeclaredmethods (); A          -         //traversal output All method declarations -          for(Method method:methods) the         { -System. out. println (method); -         } -     } +  -}

MethodProvides information about a single method (and how to access the method) on a class or interface. The method that is reflected may be a class method or an instance method, including an abstract method.

MethodExtended conversions are allowed to match the formal parameters of the underlying method to be invoked, but are thrown if a narrowing conversion is to be made IllegalArgumentException .

2: Call method by Reflection

1 import Java.lang.reflect.Method;2 3  Public classInvoketester4 {5      Public intAddintPARAM1,intparam2)6     {7         returnParam1 +param2;8 9     }Ten  One      Publicstring Echo (String message) A     { -         return "Hello:"+message; -     } the  -      Public Static voidMain (string[] args) throws Exception -     { -  +         //Previous conventional means of execution -Invoketester tester =NewInvoketester (); +System. out. println (Tester.add (1,2)); ASystem. out. println (Tester.echo ("Tom")); atSystem. out. println ("---------------------------"); -  -         //by way of reflection -  -         //The first step is to get the class object -         //the previous method is: the Class.forName () method gets in         //here is the second method, class name. -Class<?> ClassType = Invoketester.class; to  +         //to generate a new object: Using the Newinstance () method -Object Invoketester =classtype.newinstance (); theSystem. out. println (Invoketester instanceof Invoketester);//Output True *  $         //calling methods by reflectionPanax Notoginseng         //first, you need to get the method object corresponding to the -Method Addmethod = Classtype.getmethod ("Add",NewClass[] {int.class, the                 int.class }); +         //The first parameter is the method name, and the second parameter is an array of class objects for the parameters required by this method A  the         //calling the target method +Object result = Addmethod.invoke (Invoketester,NewObject[] {1,2 }); -System. out. println (Result);//at this point, result is an integer type $          $         //call a second method -Method Echomethod = Classtype.getdeclaredmethod ("Echo",NewClass[]{string.class}); -Object result2 = Echomethod.invoke (Invoketester,Newobject[]{"Tom"}); theSystem. out. println (RESULT2); - Wuyi     } the}

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 ;      = 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):

1  Class<?> ClassType = Customer. class ; 2 3     // gets the constructor object, where the first parameterless construction method is obtained. 4     Constructor cons = Classtype.getconstructor (new  class[] {}); 5 6     // to build an object by constructing a method 7     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 ;     = Classtype.getconstructor (new class[] {String.  Classint. class });     = Cons2.newinstance (new object[] {"zhangsan",+});

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.

The reflection mechanism of Java

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.