Reflection of the Java Core Technology point

Source: Internet
Author: User

1. Overview

Java Reflection is a mechanism that allows us to get internal information about the class's methods, properties, parent classes, interfaces, and so on at run time. in other words, reflection is essentially a "reverse" process. When we create an instance of a class from new, it is actually built by the Java Virtual machine at run time based on the class object of the classes, and the reflection is to get its definition information through a class object, so that we can access its properties, methods, and know the parent class, What interfaces and other information are implemented.

2. Class

We know that using Javac can compile. java files into a. class file, which contains our original definition information (parent class, interface, constructor, property, method, etc.) for the class. The class file is ClassLoader loaded into the Java Virtual Machine (JVM) at run time. When a. class file is loaded, the JVM generates a class object for it, and the object that we instantiate in the program is actually constructed at runtime based on the corresponding class object. Specifically, this class object is actually an instance of the Java.lang.class<t> generic class, such as the Class<myclass> object, which is a class<t> that encapsulates the definition information for the MyClass class. Instance. Since the Java.lang.class<t> class does not have a public constructor, we cannot instantiate the class directly, and we can get a class object in the following ways.

In the following explanation, we will take the people class and the student class as an example:

1 public class People {2     private String name; 3     private int age; 4      5 public     people (String name, Int. age) {6         this.name = name, 7         this.age = age, 8     } 9     public     int Getage () {One         return age;12     }13 1 4 Public     String GetName () {         name;16}17, public     void Setage (int.) {         This.age = a ge;20     }21 public     void SetName (String name) {         this.name = name;24}25-     public     void Speak () {         System.out.println (getName () + "+ getage ());     
1 public class Student extends people {2     private int grade; 3      4 public     Student (String name, Int. age) {5         Super (name, age); 6     } 7      8 public     Student (String name, int. int, int grade) {9         super (name, age),         This.grade = grade;11< c9/>}12     public     int Getgrade () {         setgrade return grade;15}16-public     void (int grade) {         This.grade = grade;19     }20     private void Learn (String course) {         System.out.println ( Name + "Learn" + course);     }24  

(1) Get the class object by its name:

If you know the name of a class at compile time, we can get its class object like this:

1 class<people> peopleclass = People.class;

There is also a way to get a class object based on the full pathname of the class, as follows:

1 class<people> peopleclass = Class.forName ("Com.test.People"); Suppose the people class is in the Com.test package

Note that the parameter of the Class.forName () method must be the full path name of a class. In fact, as long as we "import com.test.People", we can directly through "people.class" to get his class object, rather than write the full path so troublesome.
(if the corresponding class is not found in Classpath when calling the Class.forName () method, the ClassNotFoundException is thrown.) )

(2) Obtain its class object from the object itself:

1 people people = New People ("Bill"), 2 class<people> peopleclass = People.getclass ();
3. Getting the constructor of a class by reflection

Once we have the people class object, we can get the original definition information of the people class through this class object. First, we get the constructor object of the people class, and with this constructor object, we can construct a people object. For example, we can add the following code to the Student.java:

1 public static void main (string[] args) {2         class<people> pClass = people.class; 3         System.out.println (PCLA SS); 4         try {5             constructor<people> Constructor = Pclass.getconstructor (String.class, Int.class); 6             People people = constructor.newinstance ("Bill", 18); 7             Obj.speak (); 8         } catch (Exception e) {9             e.printstacktrace ();         }11}

In line 4th, we call the GetConstructor method to get a constructor object for the people class, because we want to get the constructor's parameter type string and int, so we pass in String.class and Int.class. With the constructor object, we can call the Newinstance method to create a people object, as shown in line 6th of the preceding code.

Note that when the Constructor, method, and Field objects of a class are obtained through reflection, the accessible flag of this object is set to true before the methods of these objects are called to suppress the Java language access check, which can increase the reflection speed. As shown in the following code:

1 constructor<people> Constructor = Peopleclass.getconstructor (String.class, Int.class); 2//Set Constructor The accessible property is ture to cancel access checks for Java 3 constructor.setaccessible (true);

4. Get the method defined in the class by reflection (1) Gets the methods defined in the current class (excluding inherited from the parent class)

To get all the methods defined in the current class can pass the Getdeclaredmethods function in class, it gets all the methods defined in the current class (including private, public, static, and so on), which returns an array of method objects. Each of these method objects represents the methods defined in a class. To get the specified method, you can call Getdeclaredmethod (String name, class...<t> parametertypes). As shown in the following code:

 1 private static void Showdeclaredmethods () {2 Student Student = new Student ("Bill", 3 method[] met Hods = Student.getclass (). Getdeclaredmethods (); 4 for (method Method:methods) {5 System.out.println ("declared Method Name:" + method.getname ()); 6} 7 8 try {9//Get Learnmethod Object (encapsulated Learn method) Learnmethod = Student.getc Lass (). Getdeclaredmethod ("Learn", string.class); 11//Get the parameter list of the Learn method and print it out. class<?>[] Paramc lasses = Learnmethod.getparametertypes (); class<?> class:paramclasses) {Sys TEM.OUT.PRINTLN ("Parameters of the Learn method:" + class.getname ()); 15}16//Determine if the Learn method is Private17 Syste M.out.println (Learnmethod.getname () + "is private" + modifier.isprivate (Learnmethod.getmodifiers () ); Learnmethod.invoke (student, "Java Reflection"); catch (Exception E){e.printstacktrace (); 22}23} 

Line 12th, by calling the Getparametertypes method of the method object to get a list of the types of the formal parameters of a way, this method returns an Class<t> array. For example, because the Learn method has only one parameter of type string, calling this method returns an Class<t> array that contains only string.class one element. (Because the returned class objects correspond to different types, we have class<?> in the code above.) )

In line 14th, we call the GetName method of the class object, which returns the full name of the class that this class object encapsulates (this example returns java.lang.String).

In line 19th, the method object is encapsulated by invoking the Invoke method of the method.


(2) Gets the public method defined in the current class and parent class

To get the current class and all public methods in the parent class can call the GetMethods function, and to get a specified public method, you can call the GetMethod method. Take a look at the following code:

1 private static void Showmethods () {2         Student Student = new Student ("Mr.simple"); 3         //Get all public methods (including the Student itself) and inherited from the parent class) 4         method[] methods = Student.getclass (). GetMethods (); 5 for         (Method method:methods) {6             System.ou T.println ("Method Name:" + method.getname ()); 7         } 8         try {9             ///Note that the public method can only be obtained through GetMethod and throws an exception if you try to get the private method             Learnmethod = Student.getclass (). GetMethod ("Learn", string.class);         catch (Exception e) {             e.printstacktrace ();         }15     }

   
5. Getting properties defined in a class by reflection
The Get property is similar to the Get method, except that the GetMethod function is replaced with Getfield,getdeclaredmethod for Getdeclaredfield.
(1) Gets the properties defined in the current class (excluding attributes inherited from the parent class)

To get all the properties defined in the current class (including various properties such as private, public, static, and so on), you can call the Getdeclaredfields function of the class object, and you can call Getdeclaredfield to get the specified property. As shown in the following code

1  private static void Showdeclaredfields () {2         Student Student = new Student ("Bill"); 3         //Gets all properties defined in the current class and explicitly Show 4         field[] fields = Student.getclass (). Getdeclaredfields (), 5 for         (Field field:publicfields) {6             System. OUT.PRINTLN ("declared Field Name:" + field.getname ()); 7         } 8  9         try {Ten             //Get the specified property one             Field Gradefield = Student.getclass (). Getdeclaredfield ("grade"); /             /Get attribute value of             System.out.println ("The Grade is:" + gradefield.getint (student))             and//Set attribute value             Gradefield.set (student),             System.out.println ("The Grade is:" + gradefield.getint (student));         (Exception e) {             e.printstacktrace ();         }20}

(2) Gets the public property defined in the current class and parent class

To get all the public properties defined in the current class and the parent class can call the GetFields function of the class object, and to get a specified public property, you can call the GetField method, as shown in the following code:

private static void Showfields () {        Student Student = new Student ("Bill");        Gets all the public properties of the current class and parent class and displays        field[] publicfields = Student.getclass (). GetFields ();        for (field Field:publicfields) {            System.out.println ("Field name:" + field.getname ());}        }

 

6. Get the parent class by reflection gets the parent class of the class and the interface implemented by the class (1)

Call the Getsuperclass method of the class object, as shown in the following code:

1 Student Student = new Student ("Bill", 2 class<?> superclass = Student.getclass (). Getsuperclass (); 3 System.out . println ("Student's Super Class is:" + superclass.getname ());

(2) Get interface

To know which interfaces a class implements, simply call the Getinterfaces method of the class object, as shown in the following code:

1 private static void Showinterfaces () {2         Student Student = new Student ("Bill", 3         class<?>[] Interfaces = Student.getclass (). Getinterfaces (); 4 for         (class<?> interface:interfaces) {5                 System.out.println (" Implements interface: "+ interface.getname ()); 6         }7}

Because the student class does not explicitly implement any interfaces, the above code will not output anything.

Reflection of the Java Core Technology point

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.