Java Reflection Mechanism Analysis Guide

Source: Internet
Author: User

is Java a dynamic language?

In general, when it comes to dynamic speaking, it means that the program structure or variable type is allowed to change while the application is running, and from this point of view, Java and C + + are not dynamic languages.

But Java has a very prominent dynamic correlation mechanism: reflection. By reflection, Java can load, detect, and use classes that are fully summed during compilation, build its object entities, invoke its methods, or set values on the property at run time. So Java is a semi-dynamic language.

The concept of Reflection:

The reflection mechanism in Java means that all the properties and methods of this class can be known in the running state for any class.

For any object, it can be called any one of its methods;

This dynamic acquisition of information and the ability to dynamically invoke object methods are known as the reflection mechanism of the Java language

Second, dynamic nature

2.1. Dynamic Nature

Generate object instances at run time;
Calling methods during run time;
Changing properties at run time

2.2, the Java reflection mechanism can realize the function

Determine the class to which any object belongs at run time
To construct an object of any class at run time
Determine the methods and properties that any of the classes have at run time
Methods to invoke any object at run time
Generating dynamic agents

2.3. Application of Java Reflection

In Java programs, there are two types of objects at run time: compile-time type and run-time type

The type at compile time is determined by the type used 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 ();
Compile-time type is person, while runtime is student

In addition, the program may also receive an externally passed object at run time, which has a compile-time type of object, but the program needs to invoke the method of the object's run-time type. For 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 might belong to, the program relies only on run-time information to discover the real information about the object and the class, and it must use the reflection

Third, the Java Reflection API

The reflection API is used to generate information about classes, interfaces, or objects in the current Java virtual machine.

Class: A reflection of the core class, you can get the properties of the class, methods and other content information.

Field class: Java.lang.reflect. Represents the properties of a class, and you can get and set the property values in the class.

Method class: Java.lang.reflect. Represents a method of a class that can be used to obtain information about a method in a class or to execute a method

Construcor class: Java.lang.reflect. Represents the construction method of a class.

Iv. getting all methods and properties

Person class

Package Com.pb.reflect.classinfo;public class Person {private string name;private string gender;private int age;private P   Erson () {//}public person (string name, String gender, Int. age) {super ();   THIS.name = name;   This.gender = gender; This.age = age;} Getter, and setter method private String GetName () {return name;} private void SetName (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.) {this.age = age;} Public String toString () {return ' name: ' +name+ ' age: ' +age;}} Using Reflection: Package Com.pb.reflect.classinfo;import Java.lang.reflect.constructor;import Java.lang.reflect.field;import Java.lang.reflect.method;import javax.swing.joptionpane;/** 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 Reflectdemo {/** constructor method */public Reflectdemo () {//user input class full path diameter//Make Using the string component string Classpsth=joptionpane.showinputdialog (NULL, "full path of the input class");       Use the Class.forName method to return the class object of the classes based on the full path of the input class, try {class CLA = Class.forName (classpsth); Using the Class object's CLA self-audit, return the method object collection methods [] Method=cla.getdeclaredmethods ();       Return all Method System.out.println ("======== Get method information ============");       For (method Meth:method) {//Iterates over the method array, and outputs the methods information System.out.println (Meth.tostring ());       } System.out.println ("======== obtains the end of method information ============");           Gets the properties of the class object using the CLA's self-audit, which returns a collection of member property Objects Field [] Field=cla.getdeclaredfields ();           System.out.println ("======== get member Attribute information ============");           for (Field F:field) {System.out.println (f.tostring ());       } System.out.println ("======== get Member Attribute information end ============");           The Get property takes advantage of the CLA's self-audit of the class object, returning the constructor method set Constructor [] constructor=cla.getdeclaredconstructors ();           System.out.println ("======== Get Member Construction method information ============"); for (Constructor constru:constructor) {               System.out.println (Constru.tostring ());   } System.out.println ("======== gets member construction method information End ============");       } catch (ClassNotFoundException e) {e.printstacktrace (); SYSTEM.OUT.PRINTLN ("Path input Error!   "); }}}package Com.pb.reflect.classinfo;public class Testreflection {public static void main (string[] args) {Reflectdemo Rd =new Reflectdemo ();}} Input Com.pb.Reflect.classinfo.Person

Results:

======== Get method information ============public java.lang.String com.pb.Reflect.classinfo.Person.getGender () public void Com.pb.Reflect.classinfo.Person.setGender (java.lang.String) public int com.pb.Reflect.classinfo.Person.getAge () public void Com.pb.Reflect.classinfo.Person.setAge (int.) Public java.lang.String Com.pb.Reflect.classinfo.Person.toString () Private java.lang.String com.pb.Reflect.classinfo.Person.getName () private void Com.pb.Reflect.classinfo.Person.setName (java.lang.String) ======== Gets the end of method information ==================== Get member Property Information ============private java.lang.String com.pb.Reflect.classinfo.Person.nameprivate java.lang.String com.pb.Reflect.classinfo.Person.genderprivate int com.pb.reflect.classinfo.person.age======== Get member property information ends ========= =========== Gets the construction method information ============private Com.pb.Reflect.classinfo.Person () public Com.pb.Reflect.classinfo.Person ( Java.lang.string,java.lang.string,int) ======== Get Construction method information End ============

V. Steps to use reflection

5.1. Steps

Java.lang.reflect

Get the Java.lang.Class object for the class you want to manipulate
Method of calling Class
Use the reflection API to manipulate this information

5.2. How to get the class object

Call the GetClass () method of an object
Person p = new person ();
Class Cla=p.getclass ();
Call the class property of a category to get the class object
Class Cls=person.class;
Using the class forname () static method
Class Cla=class.forname ("Full path of the class");
The GetClass () method of the second mode object

The person class, because the method public is constructed because the object is being declared

Package Com.pb.reflect.classinfo;public class Person {private string name;private string gender;private int age;public Pe   Rson () {//}public person (string name, String gender, Int. age) {super ();   THIS.name = name;   This.gender = gender; This.age = age;} Getter, and setter method private String GetName () {return name;} private void SetName (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.) {this.age = age;} Public String toString () {return ' name: ' +name+ ' age: ' +age;}} Using Reflection: Package Com.pb.reflect.classinfo;import Java.lang.reflect.constructor;import Java.lang.reflect.field;import Java.lang.reflect.method;import javax.swing.joptionpane;/** 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. The method that invokes the class object returns the method and property information that accesses the */public Reflectdemo (person p) {Class cla=p.getclass (); Returns a collection of method objects using the Class object's CLA self-audit [] Method=clA.getdeclaredmethods ();   Return all Method System.out.println ("======== Get method information ============");   For (method Meth:method) {//Iterates over the method array, and outputs the methods information System.out.println (Meth.tostring ());   } System.out.println ("======== obtains the end of method information ============");       Gets the properties of the class object using the CLA's self-audit, which returns a collection of member property Objects Field [] Field=cla.getdeclaredfields ();       System.out.println ("======== get member Attribute information ============");       for (Field F:field) {System.out.println (f.tostring ());   } System.out.println ("======== get Member Attribute information end ============");       The Get property takes advantage of the CLA's self-audit of the class object, returning the constructor method set Constructor [] constructor=cla.getdeclaredconstructors ();       System.out.println ("======== Get Member Construction method information ============");       for (Constructor constru:constructor) {System.out.println (constru.tostring ()); } System.out.println ("======== gets member construction method information ends ============");}} Test class Package Com.pb.reflect.classinfo;public class Testreflection {public static void main (string[] args) {person p=new P   Erson (); Reflectdemo rd=New Reflectdemo (P);}} ======== Get method information ============public java.lang.String com.pb.Reflect.classinfo.Person.getGender () public void Com.pb.Reflect.classinfo.Person.setGender (java.lang.String) public int com.pb.Reflect.classinfo.Person.getAge () public void Com.pb.Reflect.classinfo.Person.setAge (int.) Public java.lang.String Com.pb.Reflect.classinfo.Person.toString () Private java.lang.String com.pb.Reflect.classinfo.Person.getName () private void Com.pb.Reflect.classinfo.Person.setName (java.lang.String) ======== Gets the end of method information ==================== Get member Property Information ============private java.lang.String com.pb.Reflect.classinfo.Person.nameprivate java.lang.String com.pb.Reflect.classinfo.Person.genderprivate int com.pb.reflect.classinfo.person.age======== Get member property information ends ========= =========== gets the member construction method information ============public Com.pb.Reflect.classinfo.Person () public Com.pb.Reflect.classinfo.Person ( Java.lang.string,java.lang.string,int) ======== Get member Construction method information ends ============

 

Vii.. Class property of the Third method class

Person class Ibid.

Test class:

Package Com.pb.reflect.classinfo;import Java.lang.reflect.constructor;import Java.lang.reflect.field;import Java.lang.reflect.method;public class Testreflection {public static void main (string[] args) {/* second method person P=new Pe   Rson ();   Reflectdemo rd=new Reflectdemo (p); */* * Third Way. Class attribute */class Cla=person.class; Using the Class object's CLA self-audit, return the method object collection methods [] Method=cla.getdeclaredmethods ();           Return all Method System.out.println ("======== Get method information ============");           For (method Meth:method) {//Iterates over the method array, and outputs the methods information System.out.println (Meth.tostring ());           } System.out.println ("======== obtains the end of method information ============");               Gets the properties of the class object using the CLA's self-audit, which returns a collection of member property Objects Field [] Field=cla.getdeclaredfields ();               System.out.println ("======== get member Attribute information ============");               for (Field F:field) {System.out.println (f.tostring ()); } System.out.println ("======== gets member genusEnd of sexual information ============ ");               The Get property takes advantage of the CLA's self-audit of the class object, returning the constructor method set Constructor [] constructor=cla.getdeclaredconstructors ();               System.out.println ("======== Get Member Construction method information ============");               for (Constructor constru:constructor) {System.out.println (constru.tostring ()); } System.out.println ("======== gets member construction method information ends ============");}}

Results:

Ditto

======== Get method information ============public java.lang.String com.pb.Reflect.classinfo.Person.getGender () public void Com.pb.Reflect.classinfo.Person.setGender (java.lang.String) public int com.pb.Reflect.classinfo.Person.getAge () public void Com.pb.Reflect.classinfo.Person.setAge (int.) Public java.lang.String Com.pb.Reflect.classinfo.Person.toString () Private java.lang.String com.pb.Reflect.classinfo.Person.getName () private void Com.pb.Reflect.classinfo.Person.setName (java.lang.String) ======== Gets the end of method information ==================== Get member Property Information ============private java.lang.String com.pb.Reflect.classinfo.Person.nameprivate java.lang.String com.pb.Reflect.classinfo.Person.genderprivate int com.pb.reflect.classinfo.person.age======== Get member property information ends ========= =========== gets the member construction method information ============public Com.pb.Reflect.classinfo.Person () public Com.pb.Reflect.classinfo.Person ( Java.lang.string,java.lang.string,int) ======== Get member Construction method information ends ============

  

 

Java Reflection Mechanism Analysis Guide

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.