Consolidating Java (vii)-----Java reflection mechanism

Source: Internet
Author: User

In general, the developer community speaks of dynamic language, which is broadly agreed to as a definition: "When a program is run, it is allowed to change the program structure or variable type, which is called Dynamic language." From this point of view, Perl,python,ruby is a dynamic language, and c++,java,c# is not a dynamic language. Although Java is not a dynamic language under such definitions and classifications, it has a very prominent dynamic correlation mechanism: Reflection. This word means "reflection, image, reflection," which is used in Java to refer to the classes that we can load, detect, and use completely unknown during compilation. In other words, a Java program can load a runtime to know the name of a class, learn its full construct (but not including the methods definition), and generate its object entities, or set values on its fields, or evoke its methods. "This passage from Baidu Encyclopedia"

Java reflection has these features:

* Determine the class to which an object belongs at run time;
* Constructs an object of any class at run time;
* Determine the member objects and methods of any class at run time;
* Methods to invoke any class at run time
* Generate dynamic agents

Next, you will understand the reflection mechanism of Java through some examples.

gets its full package name and class name based on the object

Abstract class Base{}class Baseext extends Base{}public class Reflection {public static void main (string[] args) {  Bas Eext Baseext = new Baseext ();//gets its full package name and class name by Object System.out.println ("Baseext object of the run-time class of the Java.lang.Class object:" + Baseext.getclass ()); System.out.println ("The class that instantiates the object Baseext is:" +baseext.getclass (). GetName ()); System.out.println ("The superclass of the class that instantiates the object Baseext is:" +baseext.getclass (). Getsuperclass (). GetName ()); System.out.println ("The superclass of the class that instantiates the object Baseext is:" +baseext.getclass (). Getsuperclass (). Getsuperclass (). GetName ());}}

Run results

The Java.lang.Class object for the run-time class of the Baseext object: Class Reflection. Baseext instantiate an Object Baseext class is: Reflection.baseext instantiates the class of the object Baseext is: Reflection.base instantiates the superclass of the class of the object Baseext is: Java.lang.Object


Induction:

The function of 1.getClass () is to return the Java.lang.Class object of the object's run-time class;

The function of 2.getSuperclass () is to return the Java.lang.Class object of the parent class of the object's class;

The function of 3.getName () is to obtain its package name and path according to class;

instantiate the class object, get the properties and methods of the class, call the methods of the class

class Base1{public int count;public void Say (String item) {System.out.println ("I Am Base1 class," +item);} public void Tell () {System.out.println ("I am not telling you that I am Base1");}} Class Base2{public string name;public void Say (string item) {SYSTEM.OUT.PRINTLN ("I Am Base2 class," +item);} public void Tell () {System.out.println ("I am not telling you that I am Base2");}}    Class info{public void GetInfo (object obj) {//Gets the class name of the obj object String className = Obj.getclass (). GetName (); try {//Instantiate a class ClassName object class<?> base = Class.forName (ClassName);//Get all properties of the class field[] fields = BASE.GETDECLAREDF Ields (); System.out.println ("Fields:"), for (Field field:fields) {//access modifier int mo = Field.getmodifiers (); string modifier = modifier.tostring (MO);//property type String type = Field.gettype (). GetName ();//property name String name = Field.getname ( ); System.out.println ("+modifier +" "+ Type +" "+name);} Get all methods of the class method[] methods = Base.getmethods (); System.out.println ("Methods:"); for (Method method:methods) {//access modifier int MMO = Method.getmodifiers (); String mmodifier = Modifier.ToString (MMO);//return type string mtype = Method.getreturntype (). GetName ();//property name string mname = Method.getname (); System.out.println ("+mmodifier +" "+ Mtype +" "+mname);}}    catch (ClassNotFoundException e) {e.printstacktrace ();}    } public void say (object obj,string Item) {//Gets the class name of the obj object String className = Obj.getclass (). GetName (); try{//Instantiate an object of class ClassName class<?> base = Class.forName (ClassName);//Call the Say method of the class to which the base object belongs. Methods method = Base.get    Method ("Say", string.class);    Method.invoke (Base.newinstance (), item);    Call the Tell method of the class that the base object belongs to Method2 = Base.getmethod ("Tell");    Method2.invoke (Base.newinstance ());    }catch (Exception e) {e.printstacktrace (); }}}public class Reflection {public static void main (string[] args) {Info info = new Info (); Info.getinfo (new Base1 ()); System.out.println ("-------------------------"); Info.getinfo (new Base2 ()); System.out.println ("-------------------------"); Info.say (new Base1 (), "Who Are You?"); System.out.println ("-------------------------"); Info.say (new Base2 ()," Who Are You? ");}} 

Operation Result:

fields:public int countmethods:public Void say public void tell public final void wait public final void wait public fin Al native void Wait public boolean equals public java.lang.String toString public native Int. Hashcode public final native Java.lang.Class getclass public Final native void notify public final native void Notifyall-------------------------field S:public java.lang.String namemethods:public Void say public void tell public final void wait public final void wait pub LIC final native void wait public boolean equals public java.lang.String toString public native int. Hashcode Public final Native Java.lang.Class getclass public final native void notify public final native void Notifyall------------------------ -I am Base1 class, who are you? I'm not going to tell you that I'm a Base1-------------------------I'm Base2, who are you? I'm not going to tell you I'm Base2.


Induction:

4.class<?> base = Class.forName (ClassName) instantiates an object of a class by calling Class.forName ();

5.getDeclaredFields () Gets the property of the class, GetMethods () Gets the method of the class, GetModifiers gets the access modifier for the property and method, and so on;

6. By invoking the method of the Say method in the Info class, the first parameter of the GetMethod method is the method name, followed by the parameter type, the method name is only written by the argument method, and the Invoke method starts with the second argument as the parameter of the called method.

In addition, we can get some other methods by reading the Java API, such as getting the constructor method, obtaining the method parameters and so on.

Well, the reflection is written here for the time being.



Consolidating Java (vii)-----Java reflection mechanism

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.