Java reflection mechanism and application

Source: Internet
Author: User

Java reflection mechanism

The Java reflection mechanism is in the running state. For any class, all attributes and methods of this class can be known; for any object, any method of this class can be called; this kind of dynamically obtained information and the function of dynamically calling object methods is called the reflection mechanism of Java language.

Java reflection Application

The Java reflection mechanism provides the following functions:

  1. Determine the class to which any object belongs at runtime;
  2. Construct any class object at runtime;
  3. Judge the member variables and methods of any class at runtime;
  4. Call methods of any object at runtime;
  5. Generate a dynamic proxy.

Common Methods

①. Determine whether the object belongs to the reflected class (isinstance)

class S { }  public class IsInstance {    public static void main(String args[]) {       try {            Class cls = Class.forName("S");            boolean b1 = cls.isInstance(new Integer(37));            System.out.println(b1);            boolean b2 = cls.isInstance(new S());            System.out.println(b2);       }       catch (Throwable e) {            System.err.println(e);       }    } }

In this example, a Class Object of the S Class is created, and then check whether some objects are s instances. The result outputs false and true. It indicates that INTEGER (37) is not, but new S () is.


②. Obtain all attribute fields of a reflection class

/*** Obtain all attribute fields of the reflection class ** @ Param ownerclass reflected class * @ return * @ throws exception */public field [] getproperty (class ownerclass) throws exception {// obtain all attribute fields of this class // field [] fields = ownerclass. getfields (); // only obtains the attribute field of the public access permission (including the parent class) Field [] fields = ownerclass. getdeclaredfields (); // only obtain the attributes of all access permissions for this class (excluding the parent class) // output all attribute fields for (INT I = 0; I <fields. length; I ++) {system. out. println ("attribute:" + fields [I]);} return fields ;}


③. Obtain a public attribute value of the reflection class

/*** Obtain a public attribute value of the reflection class ** @ Param ownerclass reflected class * @ Param fieldname attribute name * @ return * @ throws exception */public object getproperty (Object owner, string fieldname) throws exception {// obtain the class ownerclass = owner of the object. getclass (); // obtain an attribute of the class field = ownerclass. getfield (fieldname); // obtain the object property = field. get (owner); // output the attribute information system. out. println (fieldname + "attribute value:" + property. tostring (); return property ;}

④. Obtain all the methods in the reflection class.

/*** Get all methods in the reflection class * @ Param ownerclass reflected class * @ return * @ throws exception */public method [] getmethods (class ownerclass) throws exception {// obtain all methods of this class // field [] fields = ownerclass. getmethods (); // method [] Methods = ownerclass. getdeclaredmethods (); // only obtain the methods (excluding the parent class) of the class for all methods (INT I = 0; I <methods. length; I ++) {system. out. println ("method:" + methods [I]);} return methods ;}

⑤ Execute a method in this part of the reflection class

/*** Execute a method in the reflection class * @ Param ownerclass reflected class * @ Param methodname method name * @ return * @ throws exception */public object invokemethod (Object owner, string methodname, object [] ARGs) throws exception {// obtain the class ownerclass = owner of the object. getclass (); // obtain a method of this class. method = ownerclass. getmethod (methodname, null); // Method for executing an object result = method. invoke (owner, argS); // output result information system. out. println ("result return value:" + result); return result ;}


Demo method:

/*** Common method for testing reflection */Public void reftest () {string classname = "com. java. reflecttest. student "; try {// Through the reflection mechanism, use the class loader to load this class <?> Stu = Class. forname (classname); object objstu = Stu. newinstance (); // obtain all attributes of the reflection class system. out. println ("\ n >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>>> \ n "); system. out. println ("Call the getproperty method to obtain all attributes of the Student Class"); getproperty (Stu); // obtain a property value of the reflection class system. out. println ("\ n >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>>> \ n "); system. out. println ("Call the getproperty method to obtain the name attribute value of the Student Class"); getproperty (objstu, "name"); // obtain all methods of the reflection class system. out. println ("\ n >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>>> \ n "); system. out. println ("Call the getmethods method to obtain all methods of the Student Class"); getmethods (Stu); // execute the getinfo Method System of the reflection class. out. println ("\ n >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>>> \ n "); system. out. println ("Call the invokemethod method and execute the getinfo method of the Student Class"); invokemethod (objstu, "getinfo", null);} catch (exception e) {e. printstacktrace ();}}


Student class used for demonstration

Package COM. java. reflecttest;/*** Student Information Class ** @ author longxuan **/public class student {/*** student ID */private string stuid; /*** student ID */Public String stuid;/***** name */private string name;/***** name */Public string name; /* ** age */private int age;/* Age */Public int age;/* class */private string classid; Public String getstuid () {return stuid;} public void setstuid (string stuid) {This. stuid = stuid;} Public String getname () {return name;} public void setname (string name) {This. name = Name;} public int getage () {return age;} public void setage (INT age) {This. age = age;} Public String getclassid () {return classid;} public void setclassid (string classid) {This. classid = classid;}/*** output student information */Public void getinfo () {system. out. println ("Student Information: \ n student ID:" + stuid + "\ t name:" + name + "\ t age:" + age + "\ t class: "+ classid);}/*** constructor */Public student () {Init ();}/*** private Initialization Method */private void Init () {This. name = "James"; this. stuid = "1001"; this. age = 14; this. classid = "a001"; this. name = Name; this. age = age; this. stuid = stuid ;}}

Running result:


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.