Reflection of the Advanced Java (Reflection mechanism)--reflection Concept and foundation

Source: Internet
Author: User

The reflection mechanism is one of the dynamics of Java, and when it comes to dynamic, we need to understand dynamic language. So what is dynamic language?

First, dynamic language

Dynamic language means that a program can change its structure at run time: New functions can be introduced, existing functions can be deleted, and other structural changes. For example, the common JavaScript is dynamic language, in addition to Ruby,python and so on is also a dynamic language, and C, C + + is not a dynamic language.

Second, is Java a dynamic language?

From the dynamic language can change the structure of the program at run time or variable type, Java and C, C + + are not dynamic language.
But Java has a very prominent dynamic-related mechanism: the reflection mechanism. Through the reflection mechanism, Java can load, detect, and use classes that are completely unknown during compilation, and can generate instances of related class objects so that it can invoke its methods or change a property value. So Java can also be considered a semi-dynamic language.

Third, reflection mechanism:

1. Reflection Mechanism Concept
The reflection mechanism in Java means that in the running state, all the properties and methods of the class can be known to any one class, and any one of them can be called any one of its methods; This dynamic acquisition of information and the ability to dynamically invoke object methods become the reflection mechanism of the Java language.

2. Reflective Applications
In Java programs, there are two types of objects running: compile-time type and run-time type.
The type at compile time is determined by the type that is useful when declaring the object, and the type of the runtime is determined by the type that is actually assigned to the object
Such as:

Person p=new Student();

Where the compile-time type is person and the run-time type is student.
In addition, the program may also receive externally-passed objects at run time, which have a compile-time type of object, but the program has methods that need to invoke the runtime type of the object. To solve these problems, the program needs to discover real information about objects and classes at run time. However, if the compiler cannot predict at all what classes the object and class belong to, the program can only rely on run-time information to discover the real information about the object and the class, which must be used to reflect.

Iv. Java Reflection API

The reflection API is used to generate information about classes, interfaces, or objects in the JVM.
-Class: Reflection of the core class, you can get the properties of the class, methods and other information.
-Field class: A class in a Java.lang.reflec package that represents a member variable of a class that can be used to get and set property values within a class.
-Method Class: A class in the Java.lang.reflec package that represents the class's methods, which can be used to obtain method information or execute methods in a class.
-Constructor class: A class in a Java.lang.reflec package that represents the constructor method of a class.

V. Steps to use reflection

1. Steps

    • Gets the class object of the classes you want to manipulate
    • Calling Methods in class classes
    • Use the reflection API to manipulate this information

2. How to get a class object

    • Call the GetClass () method of an object
Person p=new Person();Class clazz=p.getClass();

Call the class property of a category to get the class object
Class clazz=Person.class;

Use the forname () static method in class classes; (Safest/Best performance)
Class clazz=Class.forName("类的全路径"); (最常用)
    • 1

3. Get method and property information

Once we have the class object for the classes we want to manipulate, we can get and view the methods and properties in the class by means of the methods in class.
Example code :

<<<<<<<<<<<<<<<<<<<<<<person class <<< <<<<<<<<<<<<<<<<<<<<<<<package reflection;PublicClass Person {private String name;Private String gender;Privateint age;PublicPerson () {}PublicPerson (string name, String gender,int age) {THIS.name = name;This.gender = gender;This.age = age; }Getter and Setter methodsPublic StringGetName () {return name; }PublicvoidSetName (String name) {THIS.name = name; }public String getgender () {return Gender } public void setGender (String Gender) {this.gender = gender;} public int getAge () {return age; } public void setAge (int age" {this.age = Age;} public String tostring () {return Span class= "hljs-string" > "name:" +name+ <<<<<<<<<<<<<<<< using Reflection <<<<<<<<<< <<<<<<<<<
Package Reflection; Import Java. lang. reflect. Constructor; Import Java. lang. reflect. Field; Import Java. lang. reflect. Method;/* * Gets the member methods and properties of the class through the full path of the user input class * declared gets all private and public * 1. Gets the class object that accesses the classes * 2. Methods that call class objects return methods and property information for accessing classes */public class Test {public static void main (string[] args) {try {//Get class object for person classes Clazz=class. forname ("Reflection. Person "); Get all method information for the person class method[] Method=clazz. Getdeclaredmethods (); for (Method M:method) {System. Out.println (M.tostring ()) .getdeclaredfields () .out.println (F.tostring ()) ;}// Gets all construction method information for the person class constructor[] Constructor=clazz.getdeclaredconstructors () Span class= "hljs-comment" >; for (Constructor c:constructor) {system.out.tostring ()) .printstacktrace () ;}}       

Output Result:

Method information:
Public java.lang.String Reflection. Person.tostring ()
Private java.lang.String reflection. Person.getname ()
private void Reflection. Person.setname (java.lang.String)
public void Reflection. Person.setage (int)
public int Reflection. Person.getage ()
Public java.lang.String Reflection. Person.getgender ()
public void Reflection. Person.setgender (java.lang.String)
Property Information:
Private java.lang.String reflection. Person.name
Private java.lang.String reflection. Person.gender
private int Reflection. Person.age
Construction method Information
Private reflection. Person ()
Public reflection. Person (Java.lang.string,java.lang.string,int)

4. Create an Object

When we get the class object of the required classes, we can use it to create objects, there are two ways to create objects:

    • Use the Newinstance () method of the class object to create an instance of the class object counterpart, but this method requires that the class object has a default empty constructor.
    • By using the class object to get the specified constructor object, and then invoking the Newinstance () method of the constructor object to create an instance of the class object corresponding to this method, you can select the constructor method to create the instance.

Example code:

Package reflection;Import Java.lang.reflect.Constructor;PublicClassDemo01 {PublicStaticvoidMain (string[] args) {try {Gets the class object of the person classes Clazz=class.forname (/** * First method to create an object *///Create object Person p= (person) clazz.newinstance () ; //set properties P.setname ( "Zhang San"); P.setage ( "male"); System.out.println (P.tostring ()); /** * Second method to create *///Get construction method Constructor c= Clazz.getdeclaredconstructor (String.class,string.class,int.class); //Create object and set properties person p1= (person) c.newinstance ( "John Doe",  "male", 20); System.out.println (P1.tostring ()); } catch (Exception e) {e.printstacktrace ();}}       

Output Result:

Name: Zhang San Sex: male Age: 16
Name: John Doe Sex: Male Age: 20

Well, the above is a brief introduction to the Java reflection mechanism, the next article I will talk about the reflection of the two specific applications, through the reflection operation annotations and through the reflection operation of generics, interested students can understand a wave.

Reflection of the Advanced Java (Reflection mechanism)--reflection Concept and foundation

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.