Java Reflection mechanism

Source: Internet
Author: User

Problem:

At run time, can you know properties and methods for a Java class, or can I invoke any of its methods?

The answer is yes, and Java provides a reflection mechanism that can be implemented.

Directory

What is the reflection mechanism of Java
The reflection API provided in the JDK
What functionality is provided by the Java reflection mechanism
Gets the class object
Gets the fields of the class
Gets the method of the class
Get the constructor of a class
Instance of new class
The function of class<t> newinstance
By means of the constructor object newinstance
Calling a function of a class
Calling the Private function
Set/Get property values for a class
Private property
Dynamically creating proxy classes
Dynamic Agent Source Code analysis
Java Reflection class<t> Type source code Analysis
Analysis of the principle of Java reflection
class file Structure
JVM load Class object, support for reflection
Application of Java Reflection

First, what is the reflection mechanism of Java

Java reflection is a key property of Java as a dynamic (or quasi-dynamic) language. This mechanism allows the program to obtain the internal information of any known name class, including its modifiers (such as public, static, etc.), superclass (such as Object), through the reflection APIs at runtime. The interfaces of implementation (for example, cloneable) also includes all the information of fields and methods, and can change the fields content or evoke methods at run time.

The Java reflection mechanism allows programs to load, detect, and use classes that are completely unknown during compilation at run time.

In other words, Java can load a runtime to know the name of class and get its full structure.

Ii. reflection API provided in JDK

Java reflection-related APIs in package Java.lang.reflect, the reflect package for JDK 1.6.0 such as:

Member interface This interface can get information about the class member (domain or method) of the latter constructor.
AccessibleObject class The class is the base class for the Domain (field) object, method object, constructor (constructor) object. It provides the ability to mark reflected objects as being used to cancel the default Java language access control check.
The array class provides a way to dynamically generate and access a Java array.
The constructor class provides information about the constructors of a class and the interfaces that access the class's constructors.
The field class provides information about the domain of a class and the interface of the domain that accesses the class.
The method class provides information about the methods of a class and the interfaces that access the methods of the class.
The modifier class provides static methods and constants for decoding class and member access modifiers.
proxy class
Provides static methods for dynamically generating proxy classes and class instances.

Iii. What functionality is provided by the Java reflection mechanism

The Java Reflection mechanism provides the following features:

Determine the class to which any object belongs at run time

To construct an object of any class at run time

At run time, the member variables and methods that any one class has

Methods that invoke either object at run time

To create a new class object at run time

When using the reflection function of Java, it is essential to get the class object first, and then get the other objects through the class object.

Here you first define the classes used for testing:

Class type{
public int Pubintfield;
Public String Pubstringfield;
private int Prvintfield;

Public Type () {
Log ("Default Constructor");
}

Type (int arg1, String arg2) {
Pubintfield = arg1;
Pubstringfield = arg2;

Log ("Constructor with parameters");
}

public void Setintfield (int val) {
This.prvintfield = val;
}
public int Getintfield () {
return Prvintfield;
}

private void Log (String msg) {
System.out.println ("Type:" + msg);
}
}

Class Extendtype extends type{
public int Pubintextendfield;
Public String Pubstringextendfield;
private int Prvintextendfield;

Public Extendtype () {
Log ("Default Constructor");
}

Extendtype (int arg1, String arg2) {
Pubintextendfield = arg1;
Pubstringextendfield = arg2;

Log ("Constructor with parameters");
}

public void Setintextendfield (int field7) {
This.prvintextendfield = Field7;
}
public int Getintextendfield () {
return Prvintextendfield;
}

private void Log (String msg) {
System.out.println ("Extendtype:" + msg);
}
}

1. Get Class object

Instances of class classes represent classes and interfaces in a running Java application. There are several ways to get class objects for classes:

Call GetClass
Boolean var1 = true;

class<?> classType2 = Var1.getclass ();

System.out.println (CLASSTYPE2);

Output: Class Java.lang.Boolean

Use the. Class syntax
class<?> classType4 = Boolean.class;

System.out.println (CLASSTYPE4);

Output: Class Java.lang.Boolean

Using the static method Class.forName ()
class<?> ClassType5 = Class.forName ("Java.lang.Boolean");

System.out.println (CLASSTYPE5);

Output: Class Java.lang.Boolean

Using the type syntax of primitive wrapper classes

This returns the native type, and the Boolean.class returns the different

class<?> classType3 = Boolean.type;

System.out.println (CLASSTYPE3);

Output: Boolean

2, get the fields of the class

A property of a class can be obtained through a reflection mechanism, and then the property value corresponding to an instance of the class is changed. The JAVA Class<t> class provides several ways to get the properties of a class.

public field GetField (String name) returns a Field object that reflects the specified common member field of the class or interface represented by this class object
Public field[] GetFields () returns an array containing some field objects that reflect all accessible public fields of the class or interface represented by this class object
public field Getdeclaredfield (String name) returns a Field object that reflects the specified declared field of the class or interface represented by this class object
Public field[] Getdeclaredfields ()
Returns an array of field objects that reflect all the fields declared by the class or interface represented by this class object

class<?> ClassType = Extendtype.class;

Get Properties using GetFields
field[] fields = Classtype.getfields ();
for (Field F:fields)
{
System.out.println (f);
}

System.out.println ();

Get Properties using Getdeclaredfields
Fields = Classtype.getdeclaredfields ();
for (Field F:fields)
{
System.out.println (f);
}

Output:

public int Com.quincy.ExtendType.pubIntExtendField

Public java.lang.String Com.quincy.ExtendType.pubStringExtendField

public int Com.quincy.Type.pubIntField

Public java.lang.String Com.quincy.Type.pubStringField

public int Com.quincy.ExtendType.pubIntExtendField

Public java.lang.String Com.quincy.ExtendType.pubStringExtendField

private int Com.quincy.ExtendType.prvIntExtendField

Visible GetFields and Getdeclaredfields differences:

GetFields returns a property that is declared public, including the definition in the parent class,

Getdeclaredfields returns all defined properties for the specified class definition, excluding the parent class.

3. Get the method of the class

A method of a class is obtained through a reflection mechanism, and then the method that corresponds to an instance of the class is called

The Class<t> class provides several ways to get a class.

Public Method GetMethod (String name, Class<?> .... parametertypes)
Returns a method object that reflects the specified public member methods of the class or interface represented by this class object

Public method[] GetMethods ()
Returns an array that contains some method objects that reflect the public member method of the class or interface represented by this class object, including those declared by it or by those classes or interfaces that inherit from the superclass and the hyper-interface.

Public Method Getdeclaredmethod (String name,class<?> .... parametertypes)

Returns a method object that reflects the specified declared method of the class or interface represented by this class object

Public method[] Getdeclaredmethods ()
Returns an array of method objects that reflect all methods of the class or interface declaration represented by this class object, including public, protected, default (package) access, and private methods, but not inherited methods

Get a function using GetMethods
class<?> ClassType = Extendtype.class;
Method[] methods = Classtype.getmethods ();
for (Method m:methods)
{
System.out.println (m);
}

System.out.println ();

Get a function using Getdeclaredmethods
Methods = Classtype.getdeclaredmethods ();
for (Method m:methods)
{
System.out.println (m);
}
Output:

public void Com.quincy.ExtendType.setIntExtendField (int)

public int Com.quincy.ExtendType.getIntExtendField ()

public void Com.quincy.Type.setIntField (int)

public int Com.quincy.Type.getIntField ()

Public final native void Java.lang.Object.wait (long) throws Java.lang.InterruptedException

Public final void Java.lang.Object.wait () throws Java.lang.InterruptedException

Public final void Java.lang.Object.wait (Long,int) throws Java.lang.InterruptedException

public boolean java.lang.Object.equals (Java.lang.Object)

Public java.lang.String java.lang.Object.toString ()

public native int Java.lang.Object.hashCode ()

Public final native Java.lang.Class Java.lang.Object.getClass ()

Public final native void Java.lang.Object.notify ()

Public final native void Java.lang.Object.notifyAll ()

private void Com.quincy.ExtendType.Log (java.lang.String)

public void Com.quincy.ExtendType.setIntExtendField (int)

public int Com.quincy.ExtendType.getIntExtendField ()

4, get the constructor of the class

A constructor for a class is obtained through the reflection mechanism, and then the constructor is called to create an instance of the class

The Class<t> class provides several methods for getting the constructor of a class.

Public constructor<t> getconstructor (class<?> ... parametertypes)
Returns a Constructor object that reflects the specified public construction method for the class represented by this class object

Public constructor<?>[] GetConstructors ()
Returns an array containing some Constructor objects that reflect all public constructors of the class represented by this class object

Public constructor<t> getdeclaredconstructor (class<?> ... parametertypes)

Returns a Constructor object that reflects the specified construction method for the class or interface represented by this class object

Public constructor<?>[] Getdeclaredconstructors ()

Returns an array of Constructor objects that reflect all of the constructor methods for the class declaration represented by this class object. They are public, protected, default (package) access, and private construction methods

Get the constructor using GetConstructors
Constructor<?>[] Constructors = classtype.getconstructors ();
for (constructor<?> m:constructors)
{
System.out.println (m);
}

System.out.println ();

Get the constructor using Getdeclaredconstructors
constructors = Classtype.getdeclaredconstructors ();
for (constructor<?> m:constructors)
{
System.out.println (m);
}

Output:
Public Com.quincy.ExtendType ()

Public Com.quincy.ExtendType ()
Com.quincy.ExtendType (int,java.lang.string)

5. Example of a new class

Creating an instance of a new class through the reflection mechanism, there are several ways to create

Call no argument ctor
1. Call the Class object's Newinstance method, which invokes the object's default constructor, and fails if no default constructor is used.

class<?> ClassType = Extendtype.class;

Object Inst = classtype.newinstance ();

SYSTEM.OUT.PRINTLN (inst);

Output:

Type:default Constructor

Extendtype:default Constructor

[Email protected]

2. Call the Newinstance method of the default constructor object

class<?> ClassType = Extendtype.class;

Constructor<?> Constructor1 = Classtype.getconstructor ();

Object Inst = constructor1.newinstance ();

SYSTEM.OUT.PRINTLN (inst);

Output:

Type:default Constructor

Extendtype:default Constructor

[Email protected]

Call with parameter ctor
3. Call the Newinstance method with parameter constructor object

Constructor<?> Constructor2 =

Classtype.getdeclaredconstructor (Int.class, String.class);

Object Inst = constructor2.newinstance (1, "123");

SYSTEM.OUT.PRINTLN (inst);

Output:

Type:default Constructor

Extendtype:constructor with parameters

[Email protected]

6. Calling the function of the class

Gets the class method object by reflection, calling the Invoke method of the field call function.

class<?> ClassType = Extendtype.class;
Object Inst = classtype.newinstance ();
Method Logmethod = Classtype.getdeclaredmethod ("Log", String.class);
Logmethod.invoke (Inst, "Test");

Output:
Type:default Constructor
Extendtype:default Constructor
Class Com.quincy.ClassT can not access a member of class Com.quincy.ExtendType with modifiers "private"

The above failure is due to the lack of permission to call the private function, where the accessible is set to true;
class<?> ClassType = Extendtype.class;
Object Inst = classtype.newinstance ();
Method Logmethod = Classtype.getdeclaredmethod ("Log", String.class);
Logmethod.setaccessible (TRUE);
Logmethod.invoke (Inst, "Test");
7. Set/Get property values for a class

Gets the Field object of the class by reflection, calling the field method to set or get the value

class<?> ClassType = Extendtype.class;
Object Inst = classtype.newinstance ();
Field Intfield = Classtype.getfield ("Pubintextendfield");
Intfield.setint (inst, 100);
int value = Intfield.getint (inst);

Iv. dynamic creation of proxy classes

Proxy mode: The role of proxy mode = provides a proxy for other objects to control access to this object.

Role of proxy mode:

Abstract role: Common interface for declaring real objects and proxy objects

Proxy role: The proxy role contains a reference to a real object, allowing you to manipulate the real object.

Real role: The real object represented by the proxy role is the object we end up referencing.

Dynamic Agent:

Java.lang.reflect.Proxy
Proxy provides a static method for creating dynamic proxy classes and instances, or a superclass of all dynamic proxy classes created by these methods

Invocationhandler
is the interface that the invocation handler implements for the proxy instance, and each proxy instance has an associated call handler. When a method is called on a proxy instance, the method call is encoded and assigned to the Invoke method of its calling handler.

A dynamic proxy is one such class:

It is the class that runs the build, at which you must provide a set of interface to it, and then the class declares that it implements these interface. You can use an instance of this class as any of these interface. Of course, this dynamic proxy is actually a proxy, it will not do a substantial job for you, in generating its instance you must provide a handler, it takes over the actual work.

When using dynamic proxy classes, we must implement the Invocationhandler interface

Steps:

1. Defining abstract Roles

Public interface Subject {

public void Request ();

}

2. Define the real role

public class Realsubject implements Subject {

@Override

public void Request () {

TODO auto-generated Method Stub

System.out.println ("Realsubject");

}

}

3. Define Proxy roles

public class Dynamicsubject implements Invocationhandler {

Private Object Sub;

Public dynamicsubject (Object obj) {

This.sub = obj;

}

@Override

public object invoke (object proxy, Method method, object[] args)

Throws Throwable {

TODO auto-generated Method Stub

System.out.println ("Method:" + method + ", args:" + args);

Method.invoke (sub, args);

return null;

}

}

4. Building Proxy objects through Proxy.newproxyinstance

Realsubject realsub = new Realsubject ();

Invocationhandler handler = new Dynamicsubject (realsub);

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

Subject sub = (Subject) proxy.newproxyinstance (Classtype.getclassloader (),

Realsub.getclass (). Getinterfaces (), handler);

System.out.println (Sub.getclass ());

5, call the method of the proxy object to invoke the real role method.

Sub. Request ();

Output:

Class $Proxy 0 New proxy object that implements the specified interface

Method:public abstract void DynamicProxy.Subject.Request (), Args:null

Realsubject methods for invoking real objects

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.