Reflection mechanism in Java

Source: Internet
Author: User

The Java reflection mechanism means that any class in the running can know that there are many member functions and member variables in this class. For any variable, you can call these methods, including private methods, this kind of dynamic retrieval of class information and dynamic calling of these classes are called reflection mechanisms in Java. Reflection mechanisms are the basis of struts2, hibernate, and spring.

The following uses a simple example to learn the reflection mechanism in Java:

Several Classes required for learning reflection: Class, field, and Method

Any object in Java has a unique class. <?> There are three main methods to obtain the class object of an object:

A) Class <?> Classtype = Class. forname ("Java. Lang. String") // obtain the Class Object of the string object

B) Class <?> Classtype = string. Class; // note that it is called by Class Name

C) Class <?> Classtype = new string (). getclass (); // The getclass method inherits from the object method. Note that the object is called.

 

 

Example 1: Create a class without using the constructor and copy the created class to another identical object.

public class Person{private int id;private String name;private int age;public int getId(){return id;}public void setId(int id){this.id = id;}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;}private void sayHello(String name){System.out.println("Hello:"+name);}}

 

Public class copytest {public static object copy (Object OBJ) throws exception {class <?> Classtype = obj. getclass (); // obtain the Class Object newobj = classtype corresponding to the OBJ object through the getclass method of the object. newinstance (); field [] fields = classtype. getdeclaredfields (); For (field: fields) {string name = field. getname (); string firstlettle = Name. substring (0, 1 ). touppercase (); string getmethodname = "get" + firstlettle + name. substring (1); string setmethodname = "set" + firstlettle + name. substring (1); system. out. println ("Get method:" + getmethodname); system. out. println ("Set Method:" + setmethodname); Method get = classtype. getdeclaredmethod (getmethodname, new class [] {}); method set = classtype. getdeclaredmethod (setmethodname, new class [] {field. getType ()}); set. invoke (newobj, get. invoke (OBJ, new object [] {});} return newobj;} public static void main (string [] ARGs) throws exception {person person1 = new person (); person1.setage (24); person1.setid (1); person1.setname ("Gavin"); person person2 = NULL; person2 = (person) Copy (person1); system. out. println ("ID:" + person2.getid () + "name:" + person2.getname () + "Age:" + person2.getage ());}}

The preceding code is explained as follows:

1. Create a person class that contains some attributes and get and set methods, as well as a private member method sayhello (string name)

2. Use the reflection mechanism in the copytest class to obtain the set and get method names of each attribute. Then, you can find these method objects by calling getdeclaredfields of the class object, and then call the invoke method in the method object to perform the operation.

 

Example 2:

This instance uses the reflection mechanism to access private member functions and private member variables of a class.

Public class callprivate {public static void main (string [] ARGs) throws exception {person per = new person (); Per. setage (25); Per. setid (2); Per. setname ("Gavin"); // use a function in the above example. In fact, you can create a person object manually to copy person = (person) copytest. copy (PER); // obtain the class object class corresponding to the person object <?> Classtype = person. class; // obtain the sayhello method object method Hello = classtype. getdeclaredmethod ("sayhello", new class [] {string. class}); Hello. setaccessible (true); // suppress access permission detection // access the private member function hello. invoke (person, new object [] {person. getname ()}); system. out. println ("----------------------------------"); // access the private member variable field = classtype. getdeclaredfield ("name"); field. setaccessible (true); field. set (person, "Aviva"); system. out. println ("modified value:" + person. getname ());}}

Note that hello. setaccessible (true) is used in this part of the Code. The function of this Code is to suppress the monitoring of access permissions, that is, it does not check whether the method is private.

By searching the help document, we will find that constructor, field, and method all inherit the accessibleobject class, and there is a method in this class:

This means that when we pass in true, we will suppress the Java syntax to check the access permission of this method.

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.