Java reflection mechanism

Source: Internet
Author: User

In the Java Runtime Environment, can I know the attributes and methods of any class? Can any method of an object be called? The answer is yes. This kind of dynamic retrieving class information and the function of dynamically calling object Methods comes from the reflection mechanism of Java. The Java reflection mechanism provides the following functions:

1. Determine the class to which any object belongs during running;
2. Construct the object of any class at runtime; (the object of a class can be constructed through the new () method at compilation)
3. Determine the member variables and methods of any class at runtime;
4. Call methods of any object at runtime;
5. Generate a dynamic proxy.

Reflection is the key to Java being considered as a dynamic (or quasi-dynamic) language, allowingProgramUse reflection APIs during execution to obtain the internal information of any class with a known name, including package, type, parameters, superclass, Implemented interfaces, inner classes, outer class, fields, constructors, methods, modifiers (such as public and static ), instances can be generated at runtime, fields content can be changed, or methods can be called (including private methods, which means we can break the class packaging mechanism through reflection ).

Generally, developersCommunityWhen it comes to dynamic languages, a general definition is:"When a program is running, the program structure and variable type can be changed. This language is called dynamic language ."From this point of view, Perl, Python, Ruby, and JavaScript are dynamic languages, C, C ++, C #, and Java are not dynamic languages.

Although Java is not a dynamic language under such definition and classification, it has a very prominent Dynamic correlation mechanism: reflection. This word refers to "Reflection, ing, reflection". In Java, it refers to classes that are completely unknown during runtime loading, exploring, and using compilation.In other words, a Java program can load a class whose name is known only at runtime, and learn its complete structure (but does not include the definition of methods ), and generate its object entity, set its fields value, or call its methods. The ability of the program to examine itself is called introspection ). Reflection and introspection are two frequently mentioned terms.

In JDK, the following classes are used to implement the Java reflection mechanism. These classes are located in the Java. Lang. Reflect package.

    • Class: represents a class. (In java. Lang)
    • Field Class: represents the member variables of the class (member variables are also called the attributes of the class ).
    • Method class: indicates the method of the class.
    • Constructor class: constructor class.
    • Array class: provides static methods for dynamically creating arrays and accessing array elements.
Field class: Provides information about the attributes of a class or interface and its dynamic access permissions. The reflected field may be a class (static) attribute or instance attribute. A simple understanding of it can regard it as a class that encapsulates the attributes of the reflection class.
Constructor class: Provides information about a single constructor of a class and its access permissions. This class is different from the field class. The field class encapsulates the attributes of the reflection class, while the constructor class encapsulates the constructor method of the reflection class.
Method class: Provides information about a single method on a class or interface. The reflected methods may be class methods or instance methods (including abstract methods ). This class is not hard to understand. It is a class used to encapsulate reflection class methods.
Class: An instance of the class indicates the classes and interfaces in the running Java application. Enumeration is a type, and annotation is an interface. Each array is a class mapped to a Class Object. All arrays with the same element type and dimension share the class object.
Object class: Each class uses an object as a superclass. All objects (including arrays) implement this class method.

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

to use reflection, you must first obtain the Class Object of the corresponding class or object and obtain the class object of a class or object in three ways:
1. use the static method of class : class Classtype = Class. forname ("Java. Lang. String");
2. Use the. Class syntax of the class : class Classtype = string. Class;
3. Applicable to the getclass () method of the Object : String S = "AA"; Class Classtype = S. getclass ();

To generate class objects through reflection, you can use either of the following methods:
1. You can generate a class object corresponding to the object, and then generate a new instance object using the newinstance () method of the Class Object:
Class <?> Classtype = string. Class;
String STR = classtype. newinstance ();
2. to generate the class object corresponding to the object, use the getconstructor () method of the Class Object to generate the constructor object, and then use the constructor object to generate a new instance object:
Class <?> Classtype = string. Class;
Constructor <?> Constructor = classtype. getconstructor ();
String STR = constructor. newinstance ();

The latter can specify a specific constructor by passing parameters to the getconstructor () method (the former can only use the default constructor that is null ):
Class <?> Classtype = object. getclass ();
Constructor <?> Constructor = classtype. getconstructor (new class [] {string. Class, Int. Class });
Object OBJ = constructor. newinstance (new object [] {"Tom", 23 });

 1   Import Java. Lang. Reflect. field;  2   Import  Java. Lang. Reflect. method;  3   4   5   Public   Class  Reflecttest {  6       Public Object copy (Object object) Throws  Exception {  7 Class <?> Classtype =Object. getclass ();  8 Object objectcopy = classtype. getconstructor ( New  Class [] {})  9 . Newinstance ( New  Object [] {});  10 Field [] fields = Classtype. getdeclaredfields ();  11           For  (Field: fields ){  12 String name =Field. getname ();  13 String firstletter = Name. substring (0, 1 ). Touppercase ();  14 String setmethodname = "set" + firstletter + name. substring (1 );  15 String getmethodname = "get" + firstletter + name. substring (1 );  16 Method setmethod = classtype. getmethod (setmethodname, New  Class [] {field. GetType ()});  17 Method getmethod = classtype. getmethod (getmethodname, New  Class [] {});  18 Setmethod. Invoke (objectcopy, New Object [] {getmethod. Invoke (object, New  Object [] {})});  19   }  20           Return  Objectcopy;  21   }  22      23       Public   Static   Void Main (string [] ARGs) Throws  Exception {  24 Customer customer = New Customer ("Tom", 23 );  25 Customer. setid (1l );  26 Reflecttest = New  Reflecttest (); 27 Customer customer2 = (Customer) reflecttest. Copy (customer );  28 System. Out. println (customer2.getid () + "," + customer2.getname () + "," + Customer2.getage ());  29   }  30   }  31   32   Class  Customer {  33       Private Long ID;  34       Private  String name;  35       Private   Int  Age;  36       37       Public  Customer (){  38   }  39       40       Public Customer (string name,Int  Age ){  41           This . Name = Name;  42           This . Age = Age;  43   }  44   45       Public  Long GETID (){  46           Return  ID; 47   }  48   49       Public   Void  Setid (long ID ){  50           This . ID = ID;  51   }  52   53       Public  String getname (){  54          Return  Name;  55   }  56   57       Public   Void  Setname (string name ){  58           This . Name = Name;  59   }  60   61       Public  Int  Getage (){  62           Return  Age;  63   }  64   65       Public   Void Setage ( Int  Age ){  66           This . Age = Age;  67  }  68 }

 

 

 

 

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.