Java Reflection Mechanism Topic

Source: Internet
Author: User

· Java Reflection

Reflection (reflection) is considered to be the key of dynamic language, and the reflection mechanism allows the program to obtain the internal information of any class by means of the Reflection API during the execution period, and can directly manipulate the internal properties and methods of arbitrary objects.

· Features provided by the Java reflection mechanism

Determine the class to which any object belongs at run time

To construct an object of any class at run time

Determine the member variables and methods that any one class has at run time

To invoke member variables and methods of any one object at run time

Generating dynamic agents

• Reflection-related major APIs:

Java.lang.Class: Represents a class

Java.lang.reflect.Method: Methods for representing classes

Java.lang.reflect.Field: A member variable representing a class

Java.lang.reflect.Constructor: The construction method of the Representative class

Class

The following method is defined in the object class, and this method is inherited by all subclasses:

Public final Class GetClass ()

The type of the return value of the above method is a class class, which is the source of the Java reflection, in fact, the so-called reflection from the running results of the program is also very well understood, that is: the object can be reflected to find out the name of the class.

• Information you can get when you look in the Mirror: properties of a class, methods and constructors, and exactly what interfaces a class implements. For each class, the JRE retains an object of the same class type for it. A class object contains information about a particular class.

· Class itself is also a category

· Class object can only be set by the system object

• A class will have only one class instance in the JVM

• A class object corresponds to A. class file that is loaded into the JVM

• Instances of each class will remember which class instance was generated by

• Complete structure of a class can be obtained by class

Common methods for class classes

Instance:

String str = "Test. Person ";

Class clazz = Class.forName (str);

Object obj = clazz.newinstance ();

Field field = Clazz.getfield ("name");

Field.set (obj, "Peter");

Object obj2 = field.get (obj);

System.out.println (OBJ2);

Instantiating class class objects (four methods)

1) Premise: If the specific class is known, the method is most safe and reliable, and the program performance is the highest, if the class attribute is obtained.

Example: Class clazz=string.class;

2) Premise: an instance of a class is known, calling the instance's GetClass () method to get the class object

Example: Class clazz = "Woaini". GetClass ();

3) Premise: A class is known to the full class name, and the class path, can be obtained through the class class static method Forname (), may throw classnotfoundexception

Example: Class clazz = Class.forName ("java.lang.String");

4) Other ways

ClassLoader cl = This.getclass (). getClassLoader ();

Class Clazz = Cl.loadclass ("Class-wide name");

The loading process of the class

When a program actively uses a class, if the class has not yet been loaded into memory, the system initializes the class with the following three steps.

ClassLoader

The class loader is used to load classes (class) into memory. The JVM specification defines two types of ClassLoader: the Startup class loader (bootstrap) and the user-defined loader (user-defined class loader). The JVM generates an initialization loader hierarchy of 3 ClassLoader at run time

1. Get a System class loader

ClassLoader ClassLoader = Classloader.getsystemclassloader ();

System.out.println (ClassLoader);

2. Get the parent class loader of the system ClassLoader, the extension class loader

ClassLoader = Classloader.getparent ();

System.out.println (ClassLoader);

3. Get the parent class loader of the extension ClassLoader, which is the boot class loader

ClassLoader =classloader.getparent ();

System.out.println (ClassLoader);

4. Test which class loader the current class is loaded by

Classloader=class.forname ("Exer2. Classloaderdemo "). getClassLoader ();

System.out.println (ClassLoader);

5. Test which class loader is loaded by the object class provided by the JDK

ClassLoader = Class.forName ("Java.lang.Object"). getClassLoader ();

System.out.println (ClassLoader);

6. A primary method for the ClassLoader:

getResourceAsStream (String str): Gets the input stream of the specified file under the Classpath

InputStream in = null;

in = This.getclass (). getClassLoader (). getResourceAsStream ("exer2//test.properties");

System.out.println (in);

Create a Class object and get the full structure of the class

1. Create the object of the class: Call the Newinstance () method of the Class object

Requirements: 1) The class must have a constructor that has no arguments.

2) The constructor of the class must have sufficient access rights

Can't I create an object without a constructor with no arguments?

No, you can instantiate an operation only if you explicitly call the constructor in the class at the time of operation and pass the parameters in. The steps are as follows:

1) The constructor for the specified formal parameter type of this class is obtained through the class Getdeclaredconstructor (Class...prarametertypes)

2) pass an array of objects into the constructor's formal parameters, which contains each parameter required in the constructor.

3) There is a method in the constructor class:

Public T newinstance (Object...initargs)

These are the places where the reflection mechanism is most applied.

1. Gets the object's class object based on the full class name

String name = "Demo." Person ";

Class Clazz =null;

Clazz=class.forname (name);

2. Call the constructor that specifies the argument structure to generate an instance of constructor

Constructor con = clazz.getconstructor (string.class,integer.class);

3. Create an object of the corresponding class from an instance of constructor and initialize the class properties

person P2 = (person) con.newinstance ("Peter", 20);

System.out.println (p2);

Field, Method, Constructor, superclass, Interface, Annotation

All the interfaces implemented

The inherited parent class

All constructors

All the way

All the field

Use reflection to obtain:

1. All the interfaces implemented

Public class<?>[] Getinterfaces ()

Determines the interface implemented by the class or interface represented by this object.

2. Inherited parent class

Public class<? Super T>getsuperclass ()

Returns the class that represents the parent class of the Entity (class, interface, base type) represented by this class.

3. All constructors

Public constructor<t>[] GetConstructors ()

Returns all public constructor methods for the class represented by this class object.

Public constructor<t>[] Getdeclareconstructors ()

Returns all the constructor methods for the class declaration represented by this class object.

· In the constructor class:

Get modifier: public int getmodifiers ();

Get method Name: Public String getName ();

The type of the obtained parameter: public class<?>[] Getparametertypes ();

4. All the methods

Public method[] Getdeclaredmethods ()

Returns all the methods of the class or interface represented by this class object

Public method[] GetMethods ()

Method that returns the public of the class or interface represented by this class object

· In the method class:

Public class<?> Getreturntype () gets all the return values

Public class<?>[] Getparametertypes () get all the parameters

public int getmodifiders () get modifier

Public class<?>[] Getexceptiontypes () Get exception information

5. All field

Public field[] GetFields ()

Returns the field for the public of the class or interface represented by this class object.

Public field[] Getdeclaredfields ()

Returns all the field of the class or interface represented by this class object

· In the field method:

public int getmodifiers () returns the modifier for this field as an integer

Public class<?> GetType () Gets the field's property type

Public String GetName () returns the name of the field.

6.Annotation related

Get Annotation (class<t> annotationclass)

Getdeclaredannotations ()

7. Generics-related

Get parent class generic type: Type Getgenericsuperclass ()

Generic type: Parameterizedtype

Gets the actual array of generic type parameters: Getactualtypearguments ()

8. Package Getpackage () for class

Calling a method in a class by reflection, specifying a property

. Call the specified method

By reflection, calls to methods in the class are done through the method class. Steps:

1. Obtain a method object by using the class GetMethod (String name,class...parametertypes) method and set the type of parameter required for this method operation.

2. The call is then made using object Invoke (Object obj,object[] args) and the parameter information for the Obj object to be set is passed to the method.

Object Invoke (Object Obj,object...args)

Description

1.Object corresponds to the return value of the original method, the Wakahara method has no return value and returns null at this time

2. If the Wakahara method is a static method, the Parameter object obj can be null at this time

3. Wakahara method parameter list is empty, then object[] args is null

4. The Wakahara method is declared private, you need to display the setaccessible (true) method of the calling method object before calling this method, which will have access to the private method.

• Call the specified property

In the reflection mechanism, you can set up and get the property contents by using the Set () and get () methods provided by the field class directly through the properties in the field class action class.

public field GetField (String name) returns the specified public field for the class or interface represented by this class object

public field Getdeclaredfield (String name) returns the specified Field for the class or interface represented by this class object.

• In field:

public object get (object obj) Gets the property content of this field on the specified object, obj

public void Set (object Obj,object value) sets the property contents of this field on the specified object, obj

Note: Under the premise that the properties in a class are set to private, when using the set () and get () methods, first use the Setaccessible (True) method in the field class to specify the property contents of this field on the object obj

public void Setaccessible (true) to make this property visible when accessing a private property.

Java Dynamic Agent

• Dynamic proxies are methods by which customers invoke other objects through a proxy class and dynamically create a proxy object for the target class as needed while the program is running.

• Dynamic Proxy usage Scenarios:

Debugging

Remote Method invocation

• Principle of proxy design mode:

Use a proxy to wrap the object, and then replace the original object with the proxy object. Any calls to the original object are passed through the proxy. The proxy object determines whether and when the method call is forwarded to the original object.

· Proxy: The operation class that is specialized to complete the agent, is the parent class of all dynamic proxy classes, and is the parent class of all dynamic proxy classes. This class dynamically generates an implementation class for one or more interface interfaces.

• Provides static methods for creating dynamic proxy classes and dynamic proxy objects

Static class<?> Getproxyclass (ClassLoader loader,class<?>...interfaces) creates a class object corresponding to the dynamic proxy classes

Static Object Newproxyinstance (ClassLoader loader,class<?>[] Interfaces,invocationhandler h) Creates a dynamic proxy object directly

Dynamic Agent Steps

1. Create a class that implements the interface Invocationhandler, which must implement the Invoke method to accomplish the agent's specific operation.

2. Create a proxy class and interface

3. Static method of passing proxy

1 newproxyinstance (ClassLoader loader, class[] interfaces, Invocationhandler h) Create a subject interface proxy2Realsubject target =NewRealsubject ();3 //Create a proxy to wrap the original implementation4Debugproxy proxy =NewDebugproxy (target);5  //Get A reference to the proxy through the Subject interface6Subject Sub =(Subject) proxy.newproxyinstance (7Subject.class. getClassLoader (),8             NewClass[] {Subject.class}, proxy);

4. Method of implementing class by calling Realsubject through subject proxy

String info = Sub.say ("Peter", 24);

SYSTEM.OUT.PRINTLN (info);

Java Reflection Mechanism Topic

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.