"Java Core Technology" type information (class object reflects dynamic proxy)

Source: Internet
Author: User

1 class objectTo understand how Rtti works in Java, you first need to know how the type information is represented at run time, which is done by the class object, which contains information about the class. The class object is used to create all "regular" objects, and Java uses the class object to perform Rtti, even if you are doing something like type conversion. Each class will produce a corresponding class object, which is saved in the. class file. All classes are dynamically loaded 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. The class object is loaded only when needed, and static initialization occurs when the class is loaded. The class loader first checks to see if the class object has been loaded, and if it is not already 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), use the function class.forname ("base") for that purpose, or use Base.class. It is interesting to note that when you use the function ". Class" To create a reference to a class object, the class object is not automatically initialized, and the class object is automatically initialized with forname (). The use of ". Class" is not automatically initialized because it is deferred to a static method (where the constructor is private) or when a very few static domains are first referenced. The following 3 steps are generally used to prepare for the use of a class:
    • Load: Done by the ClassLoader, find the corresponding bytecode, create 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 static initialization block
 Public classBase {Static intnum = 1; Static{System.out.println ("Base" +num); }} Public classMain { Public Static voidMain (string[] args) {//static blocks are not initializedClass clazz1 = Base.class; System.out.println ("------"); //is initializedClass clazz2 = Class.forName ("zzz. Base "); }}

check before type conversionThe compiler will check whether the type down is legal and throws an exception if it is not legal. You can use instanceof to judge the type before you convert it down.
classBase {}classDerivedextendsBase {} Public classMain { Public Static voidMain (string[] args) {Base base=NewDerived (); if(BaseinstanceofDerived) {           //Here you can convert downward.System.out.println ("OK"); }       Else{System.out.println ("Not OK"); }    }}

2 Reflection run-time informationIf you do not know the exact type of an object, Rtti can tell you, but there is a precondition: This type must be known at compile time to use Rtti to identify it. The class class supports reflection with the Java.lang.reflect class library, which contains the field, method, and constructor classes, which are created by the JVM at startup to represent the corresponding members of the unknown class. The reflection mechanism is nothing magical, and when dealing with an object of unknown type through reflection, the JVM simply examines the object to see which particular class it belongs to. Therefore, the class's. 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 that: RTTI, the compiler opens and checks the. class file at compile time, the runtime opens and checks the. class file
classBase {}classDerivedextendsBase {} Public classMain { Public Static voidMain (string[] args) {Base base=NewDerived (); if(BaseinstanceofDerived) {           //Here you can convert downward.System.out.println ("OK"); }       Else{System.out.println ("Not OK"); }    }}

3 Dynamic AgentsThe proxy pattern is intended to provide additional or different operations, whereas objects inserted to replace "real" objects involve communication with the "actual" object, so the agent typically acts as a middleman. The dynamic agent of Java is a step ahead of the idea of the agent, which dynamically creates and proxies and dynamically handles calls to the proxy method. All calls made on the dynamic agent are redirected to a single calling processor, and its job is to reveal the type of invocation and determine the appropriate policy. The following is an example of a dynamic proxy:
 Public InterfaceHello {voiddosomething ();}  Public classHelloimplImplementsHello {@Override Public voiddosomething () {System.out.println ("Helloimpl dosomething"); }} /*** proxy class*/ Public classProxyhandlerImplementsInvocationhandler {PrivateObject proxyed;  PublicProxyhandler (Object proxy) {proxyed=proxy; } @Override PublicObject Invoke (Object proxy, Method method, object[] args)throwsInvocationTargetException, illegalaccessexception {System.out.println ("Proxy working"); returnMethod.invoke (proxyed, args); }}  Public Static voidMain (string[] args) {Hello Hello=NewHelloimpl (); Hello Proxy= (hello) proxy.newproxyinstance (hello).class. getClassLoader (),NewClass[]{hello.class},NewProxyhandler (hello)); Proxy.dosomething ();}

Output Result:

By calling the proxy static method Proxy.newproxyinstance () You can create a dynamic proxy, which requires a class loader, a list of interfaces (not classes or abstract classes) that you want the proxy to implement. and an implementation class for Invocationhandler. Dynamic agents can redirect all calls to the calling processor, so the handler's constructor is typically called to pass a reference to an "actual" object, which forwards the calling processor when it executes the mediation task. Reference: 1. "Java Programming Ideas" Dynamic Agent Chapter 2. Deep understanding of Java Reflection

"Java Core Technology" type information (class object reflects dynamic proxy)

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.