Java Reflection Mechanism Learning notes and example code

Source: Internet
Author: User
Tags object object

API for Java Reflection

Several classes that are often used in reflection are as follows:

In the Java.lang package:

--class class: Represents a Class

In Java, regardless of how many objects of a class are generated, these objects will correspond to the same class object

In the Java.lang.reflect package:

--field class: A member variable representing a class (a property of a class)

--method class: A method that represents a class, a method that corresponds to an object

--constructor class: A method of constructing a representative class

--array class: Provides a static method for dynamically creating an array, and for accessing the elements of an array

To invoke a method in a class by using the reflection mechanism:

1. Get the Class object

There are three common methods:

A) obtained through the static method of class forname (parameter: Package name + class name):

class<?> ClassType = Class.forName ("java.lang.String");

b) obtained by means of the class name + point class:

class<?> C = string.class;

Obtained by means of the getclass of the object of the class:

String str = "Test";

class<?> Typeclass = Str.getclass ();

2. Instantiate an object of this class

Two methods:

A) created by the Newinstance method of the Class object (this method applies only to the parameterless construction method):

class<?> ClassType = Class.forName ("java.lang.String");

Object obj = = classtype.newinstance ();

b) By getting the object of the Constructor constructor class, and then by the object's Newinstance (Object ... Initargs) method, obtain:

class<?> ClassType = Cus.getclass ();

Constructor Con

= Classtype.getconstructor (New Class[]{string.class,int.class});

Object Object

= Con.newinstance (New Object[]{cus.getname (), Cus.getage ()});

The method that writes two parameters as class[]{} and new object[]{} is equivalent to a)

3. Get the method object for the target methods

Method method = Classtype.getmethod (methodname,new class[]{parameter type. Class});

4. Use the method object to invoke the target approach:

Object result = Method.invoke (object,new object[]{});

Where object is the one that owns the method, object[]{} is the parameter of the method

5. Get the property value in the class, get value, set assignment

Get Property List

Field fields[] = Classtype.getdeclaredfields ();

Field field = Classtype.getdeclaredfields (attribute name);

Gets the property name corresponding to the Field object

Field.set (Object of class, value);

Assigning a new value to a property

Example: Accessing private-modified methods and properties

Use the reflection mechanism to access the following classes:

 Public class private{    Private" Zhang San ";         Private String getName ()    {        return  name;}    }

Change the name value of the private modifier in the class to "John Doe" and call the GetName method with the reflection mechanism to return the modified value.

Package Com.wangzhuo.reflect;import Java.lang.reflect.constructor;import java.lang.reflect.field;import Java.lang.reflect.Method; Public classprivatetest{ Public Static voidMain (string[] args) throws Exception {//get the class object for the private class&nbsp; class<?> ClassType = Class.forName ("com.wangzhuo.reflect.Private"); &nbsp;//gets the constructor object that corresponds to its construction methodConstructor con = classtype.getdeclaredconstructor (Newclass[]{}); &nbsp;//Create a Private objectObjectObject=con.newinstance (Newobject[]{});&nbsp;//Gets the Field object that corresponds to the Name property in the private classField field = Classtype.getdeclaredfield ("name");&nbsp;//Set bypass Java access control detectionField.setaccessible (true); &nbsp;//gets the value before the modificationObject str = field.Get(Object); &nbsp; System. out. println ("Modify the value of the previous name:"+(String) str); &nbsp;//Assigning a value to the Name propertyField.Set(Object,"John Doe"); &nbsp;//gets the method object corresponding to the GetName methodsMethod Getnamemethod = Classtype.getdeclaredmethod ("GetName",Newclass[]{}); &nbsp;//Set bypass Java access control detectionGetnamemethod.setaccessible (true); &nbsp;//call method, return valueObject o = Getnamemethod.invoke (Object,Newobject[]{}); System. out. println ("the value of name after modification:"+(String) o); }}

Java Reflection Mechanism Learning notes and example code

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.