Deep understanding of Java reflection _java

Source: Internet
Author: User
Tags constructor reflection

To understand the principle of reflection, you first need to understand what type information is. Java lets us identify objects and classes at run time, mainly in 2 ways: One is the traditional rtti, it assumes that we already know all the type information at compile time, and the other is the reflection mechanism, which allows us to discover and use class information at runtime .

1, Class object

To understand how Rtti works in Java, you first need to know how type information is represented at runtime, which is done by a class object that contains information about the class. The class object is used to create all the "normal" objects, and Java uses the class object to perform the RTTI, even if you are performing an operation like a type conversion.

Each class produces a corresponding class object, which is saved in the. class file. All classes are loaded dynamically into the JVM when they are first used, and the class is loaded when the program creates a reference to a static member of the class. Class objects are loaded only when they are needed, and static initialization occurs when the class is loaded.

public class Testmain {public
static void Main (string[] args) {
System.out.println (xyz.name);
}
}
Class XYZ {public
static String name = ' Luoxn28 ';
static {
System.out.println ("xyz static Block");
}
Public XYZ () {
System.out.println ("XYZ constructs");
}

The output results are:

The class loader first checks whether the class object has been loaded, and if it has not already been loaded, the default ClassLoader will look for the corresponding. class file based on the class name.

To use type information at run time, you must get a reference to the class object of the object (such as the class base object), either by using functional Class.forName ("base") or by using Base.class. Note that it is interesting that the class object is not automatically initialized when you use the function ". Class" To create a reference to the class object, and the class object is automatically initialized with forname (). The preparation for using a class typically has the following 3 steps:

• Load: The class loader completes, finds the corresponding bytecode, and creates a class object

• Links: Validating bytecode in classes, allocating space for static domains

• Initialize: If the class has a superclass, initialize it, execute the static initializer and the static initialization block

public class Base {
static int num = 1;
static {
System.out.println ("Base" + num);
}
}
public class Main {public
static void Main (string[] args) {
//does not initialize static block
class clazz1 = Base.class;
SYSTEM.OUT.PRINTLN ("------");
Initializes
the Class clazz2 = Class.forName ("zzz. Base ");
}

2. Check before type conversion

The compiler checks whether the type downward transition is legal and throws an exception if it is illegal. You can use instanceof to determine the type before you convert it down.

Class Base {}
class Derived extends base {} public
class Main {public
static void Main (string[] args) {
   
    base Base = new Derived ();
if (base instanceof Derived) {
///Here the SYSTEM.OUT.PRINTLN can be converted down
("OK");
}
else {
System.out.println ("not OK");}}

   

3, Reflection: Run-time class Information

If you don't know the exact type of an object, Rtti can tell you, but there is a prerequisite: This type must be known at compile time, so that you can use Rtti to identify it. The class class, together with the Java.lang.reflect class library, supports reflection, which contains field, method, and constructor classes, which are created by the JVM at startup to represent the corresponding members of the unknown class. In this way, you can use Contructor to create a new object, get and modify the fields associated with a Field object in the class with the Getting () and set () methods, and Invoke () methods to call the methods associated with the method object. In addition, many convenient methods, such as GetFields (), GetMethods (), and GetConstructors (), can be invoked to return an array of fields, methods, and constructor objects so that the object information can be completely determined at run time. And you don't need to know anything about the class at compile time.

The reflection mechanism is nothing magical, and when dealing with an object of unknown type through reflection, the JVM simply checks the object to see which particular class it belongs to. Therefore, the. Class of that class must be available to the JVM, either on the local machine or from the network. So the real difference between Rtti and reflection is only:

Rtti, the compiler opens and checks the. class file at compile time

• Reflection, opening and checking. class files at run time

public class Person implements Serializable {
private String name;
private int age;
Get/set method
} public
static void Main (string[] args) {person person
= new Person ("luoxn28");
Class clazz = Person.getclass ();
field[] fields = Clazz.getdeclaredfields ();
for (Field field:fields) {
String key = Field.getname ();
PropertyDescriptor descriptor = new PropertyDescriptor (key, clazz);
Method method = Descriptor.getreadmethod ();
Object value = Method.invoke (person);
SYSTEM.OUT.PRINTLN (key + ":" + value);
}

The above call to the class's get function through the Getreadmethod () method lets you invoke the class's set method through the Getwritemethod () method. Normally, we don't need to use reflection tools, but they are more useful in creating dynamic code, and reflection is used in Java to support other features, such as serialization and JavaBean of objects.

4. Dynamic Agent

Agent mode is an object that is inserted to replace an "actual" object in order to provide additional or different operations, which involve communication with an "actual" object, so the agent usually acts as a middleman. The Java dynamic Proxy is a step closer than the idea of an agent, which dynamically creates and proxies and dynamically processes calls to the proxy methods. All calls made on a dynamic proxy are redirected to a single call processor, which works by revealing the type of invocation and determining the appropriate policy. The following is an example of a dynamic proxy:

Interfaces and implementation classes:

Public interface Interface {
void dosomething ();
void SomethingElse (String arg);
}
public class Realobject implements Interface {public
void dosomething () {
System.out.println ("dosomething.");
}
public void SomethingElse (String arg) {
System.out.println ("SomethingElse" + arg);
}

Dynamic Proxy Object Processor:

public class Dynamicproxyhandler implements Invocationhandler {
private Object proxyed;
Public Dynamicproxyhandler (Object proxyed) {
this.proxyed = proxyed;
}
@Override Public
object Invoke (Object proxy, Method method, object[] args) throws Illegalaccessexception, IllegalArgumentException, InvocationTargetException {
System.out.println ("the agent worked.");
Return Method.invoke (proxyed, args);
}

Test class:

public class Main {public
static void Main (string[] args) {
realobject real = new Realobject ();
Interface proxy = (Interface) proxy.newproxyinstance (
Interface.class.getClassLoader (), new class[] { Interface.class},
new Dynamicproxyhandler (real);
Proxy.dosomething ();
Proxy.somethingelse ("Luoxn28");
}

The output results are as follows:

You can create a dynamic proxy by calling the proxy static method Proxy.newproxyinstance (), which requires a class loader, a list of interfaces (not classes or abstract classes) that you want the broker to implement. and an implementation class for Invocationhandler. A dynamic proxy can redirect all calls to the calling processor, so the processor's constructor is usually invoked to pass a reference to an "actual" object, thus calling the processor to forward the request when performing a mediation task.

The above is a small set for you to introduce the in-depth understanding of Java reflection, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.