Java proxy summary, java Summary

Source: Internet
Author: User

Java proxy summary, java Summary

I learned the Java proxy on the Internet and took notes and summarized the code.


I. Purpose of Using proxy

1. method call of a route to a remote server

2. Associate User Interface events and actions during the program running

3. Call methods for debugging and tracing



2. Classes and interfaces required for proxy implementation include:

1. Proxy class used to generate Proxy classes

2. The interface to be implemented by the proxy class. Moveable is used here.

3. Call the processor interface InvocationHandler

4. The specific proxy class. Here it is Tank, which implements the Mobeable interface.

5. The package class that calls the processor interface. Here is TimeHandler.


3. the Proxy class is dynamically generated in the Proxy class and must implement the interface implemented by the Proxy class. The Proxy class has the following methods:

1. specify all the methods required by the interface. Here is Moveable.

2. All methods in the Object class, such as toString () and equals (), because the Object is a superclass of all classes.



In the following example, the proxy logic to be implemented is that the Tank Class records the current time before and after each move () method call.


First is the test class

package proxy;import java.io.IOException;import java.lang.reflect.InvocationTargetException;public class ProxyTest {    public static void main(String[] args) throws SecurityException, IllegalArgumentException, IOException, ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {        Tank t=new Tank();        InvocationHandler h=new TimeHandler(t);        Moveable m=(Moveable) Proxy.newProxyInstance(Moveable.class,h);        m.move();    }}



Proxy class Interface

package proxy;public interface Moveable {public void move();}

Proxy class

package proxy;public class Tank implements Moveable{    @Override    public void move() {        Thread t=new Thread();        t.start();        try {            t.sleep(2000);        } catch (InterruptedException e) {            e.printStackTrace();        }        System.out.println("moving...");    }


Time Processing wrapper, constructor needs to pass the object to be proxy

package proxy;import java.lang.reflect.Method;import java.util.Date;public class TimeHandler implements InvocationHandler {Object target;public TimeHandler(Object target){super();this.target=target;}@Overridepublic void invoke(Object o,Method m) {System.out.println("start time:"+new Date().toLocaleString());try{m.invoke(target);}catch(Exception e){e.printStackTrace();}System.out.println("end time:"+new Date().toLocaleString());}}





The most important Proxy

Package proxy; import java. io. *; import java. lang. reflect. *; import java.net. *; import javax. tools. javaCompiler; import javax. tools. javaCompiler. compilationTask; import javax. tools .; public class Proxy {public static Object newProxyInstance (Class intrfc, InvocationHandler h) throws IOException, ClassNotFoundException, SecurityException, NoSuchMethodException, expiration, InstantiationException, expiration, InvocationTargetException {String mthStr = ""; // used to save the detailed implementation of all methods inherited from the intrfc Method [] methods = intrfc. getMethods (); // used to save all Method names of the intrfc for (Method m: methods) {mthStr + = "@ Override" + "" + "public void" + m. getName () + "() {" + "try {" + "Method md =" + intrfc. getName () + ". class. getMethod (\ "" + m. getName () + "\"); "+" h. invoke (this, md); "+"} catch (Exception e) {"+"} "+"} ";} String str =" import java. lang. reflect. method; "+" public class MyProxy implements "+ intrfc. getName () + "{" + "proxy. invocationHandler h; "+" public MyProxy (proxy. invocationHandler h) {"+" this. h = h; "+"} "+ mthStr +"} "; String fileName =" D:/Workspaces/Eclipse/DesignPattern/src // MyProxy. java "; File f = new File (fileName); FileWriter fw = new FileWriter (f); fw. write (str); fw. flush (); fw. close (); // compileJavaCompiler compiler = ToolProvider. getSystemJavaCompiler (); StandardJavaFileManager fileMgr = compiler. getStandardFileManager (null, null, null); Iterable units = fileMgr. getJavaFileObjects (fileName); CompilationTask task = compiler. getTask (null, fileMgr, null, units); task. call (); fileMgr. close (); // load enter the memory URL [] urls = new URL [] {new URL ("file:/" + "D: /Workspaces/Eclipse/DesignPattern/src/")}; URLClassLoader ul = new URLClassLoader (urls); Class c = ul. loadClass ("MyProxy"); // The object created through the Class instance must contain the default constructor. // The TimepProxy Class does not contain the default constructor, therefore, you can only create the Constructor ctr = c. getConstructor (InvocationHandler. class); Object m = ctr. newInstance (h); return m ;}}
Core Part of proxy implementation

1. The proxy class only contains the InvocationHandler h instance that calls the processor;

2. the proxy class implements all the methods in the interfaces implemented by the proxy class, and submits the implementation details to the calling processor h. invoke (this, md );

3. Obtain the Class Object of the proxy Class through compilation, Class Loader, and other technologies.

4. assign a value to the Proxy class and construct the Proxy object through the call processor object passed by Proxy. newProxyInstance ().

5. Return the created proxy object to the customer.



What is the use of the java proxy mode? It is not enough to call the implementation class directly.

Provides a proxy for other objects to control access to this object.
Proxy is a useful mode with many variants. The application scenario covers the large structure from a small structure to the entire system. We may have the concept of proxy server. The concept of proxy can be interpreted: there is an intermediate layer between the starting point and the destination, meaning proxy.
For details, refer to the java Design Pattern manual.
 
Java learning experience?

The first step to learning Java is to install JDK and write a Hello World. In fact, JDK learning is not that simple. There are two problems with JDK that are easily plagued by Java programmers: one is the CLASSPATH problem. In principle, it is necessary to understand how the JRE ClassLoader loads the Class. The other is the package and import problems, how to find the path of the class. By clarifying these two problems, we have removed the biggest obstacle to learning Java and using JDK. We recommend that you take a look at Wang Sen's "Java deep Adventure" and discuss these two issues in depth.

The second step is to learn the Java syntax. Java syntax is similar to C ++. Basically, the mainstream programming languages are not class C, but class C ++. There is no new things, so the syntax is learned, about half a day is enough. The only thing to note is that there are several keywords that are not easy to understand: public, protected, private, static, when to use, why to use, and how to use, it may take a long time for someone to give me some advice. But later I saw Thinking in Java, which mentioned these concepts.

The third step is to learn the features of Java's object-oriented programming language. For example, inheritance, constructor, abstract class, interface, method polymorphism, overload, overwrite, and Java exception handling mechanism. For a person without an object-oriented language background, I think this process takes a long time, because I have no C ++ experience before learning Java and only C experience, it took me about a month to fully understand these concepts. I tried to repeat, modify, and try the examples in the book and read them over and over again, after reading the past, I had to read it five times before I fully realized it. However, I think if I have C ++ experience, it may take a day or two. In this process, you can take a look at Thinking in Java, which provides a thorough explanation of object-oriented. Unfortunately, I didn't see this book when I was studying it, so I spent a lot of time learning it through my own attempts and guesses.

Step 4: Get familiar with Java class libraries. The Java base library is the jre \ lib \ rt. jar package under the JDK installation directory. Learning the basic library is to learn rt. jar. There are many classes in the basic class library. It is said that there are more than 3000, but for us, there are only four at the core:
Java. lang .*;
Java. io .*;
Java. util .*;
Java. SQL .*;

The four packages of learning, each of which can be written as a thick teaching material, and o'reilly does. I think it is impossible to study by reading four books if the time is too short. I think the better way to learn is as follows:
First, read the entire package framework and understand the composition of the class, interface, and exception of the entire package. It is best to find an article about the entire package framework. The first few chapters of these books that specifically introduce the package should be the introduction of these general frameworks.

Understanding the overall framework of the package is not to be familiar with the usage of each class. Remember what attributes and methods it has. I cannot remember it. Instead, you need to know what types of packages constitute, what are the purposes of these classes, and what functions are completed by the core classes. During training, I usually talk about a package in a class, so it is impossible to describe the usage of each class in detail. However, I have repeatedly stressed that, what I want to tell you about these packages is not to tell you how class methods are called, nor to remember the class method calls, but to understand, java provides us with classes, where each class is used, and when I encounter a problem, I know which class or which combination of classes can solve my problem, that 'all !, When writing a program, you only need to know which class to use to complete your work. When coding, the specific method call is to write code while querying Documenta ...... the remaining full text>

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.