Java Dynamic Proxy

Proxy model

Proxy model

** Proxy pattern ** (Proxy pattern) 23 types of design model No. 1, Java-like dynamic proxy model. Is it a proxy model for the nursery staff? Bottom surface proxy Schematic UML graphics: 2.png

Schematic Participants:

Proxy Schematic Example Child

One representative of the fixed neck "movable" traffic tool interface:

public interface Moveable {
    /**
     *Movement specified distance,Since the kilometer
     * @param km mobile distance
     */
    void move(Integer km);
}

Interface example: Metro (subway), type implementation Moveable interface move method, parallel model interface method.

public class Metro implements Moveable {
    @Override
    public void move(Integer km) {
        try {
            System.out.println("Metro is moving ...");
            Thread.sleep(km * 1000);  //Imitation transfer time
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

However, the test method can be performed by Jian Jian. Performance Proxy:

public class PerformanceProxy implements Moveable {
    private Moveable m;
    public PerformanceProxy(Moveable m) {
        this.m = m;
    }
    @Override
    public void move(Integer km) {
        long start = System.currentTimeMillis(); //Recording method Start time for adjustment
        m.move(km);                              //Method adjustment
        long end = System.currentTimeMillis();   //Method cohesive time
        System.out.println("When worn: " + (end - start)/1000.0); // 计算When worn
    }
}

Measurement proxy model:

public static void main(String[] args) {
    new PerformanceProxy(new Metro()).move(5);
}
----Test results----
Metro is moving ...
When worn: 5.005

Completion of a model example of a proxy. Demand measurement and other transportation tools (airplane, high speed rail) performance time, demand 让 Other 们 (airplane, high speed rail) actual Moveable connection, measurement time, general example Individual non-demand self-actual measurement test).

This sample, PerformanceProxy can be owned, actually moved. Degrees of other agents, Degrees of polynomials, Degrees of polynomials, Degrees of polynomials, etc., Tracking Proxy of demand, Logging Proxy, etc. Naturally, this is a trivial proxy city, a practical Moveable interface, and so on.

public static void main(String[] args) {
    Plane plane = new Plane();
    PerformanceProxy pp = new PerformanceProxy(plane);
    LoggingProxy lp = new LoggingProxy(PerformanceProxy);
    lp.move();
}

Static surrogate

Deputy static state?

Top-top example of the image, first compilation, Yukio Gendai, self-acting acting, re-editing. This sample, before the introduction of the program, the proxy type, the proxy type. Class sentence (binary number sentence), the existence of the substitute, the static state substitute.

Dynamic proxy

Java standard provided Dynamic Proxy function, live-time dynamic proxy example. Dynamic agency Actually, the process of passing the JDK, the runtime of the dynamic state, the class character, and the parallel loading process. General surface static surrogate example Child dynamic surrogate Realization:

public static void main(String[] args) {
    final Metro metro = new Metro();
    Moveable m = (Moveable) Proxy.newProxyInstance(Metro.class.getClassLoader(), //Substitute class loader
            new Class[]{Moveable.class}, //Afferent interface Realistic interface
            new InvocationHandler() {  //Methodical InvocationHandler for Afferent Processing(Anonymous)
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // 1
                    long start = System.currentTimeMillis();
                    Object res = method.invoke(metro, args); // 2
                    long end = System.currentTimeMillis();
                    System.out.println("When worn: " + (end - start)/1000.0);
                    return res; // 3
                }
            });
    m.move(5);
}

// 1.invoke Medium number of arguments proxy Action state Established proxy; method Interface method: Kane-jiri unequal method 做 unequal processing.
// 2. method.invoke(metro, args)Equivalence relations metro.move(), This sum js intermediate function.call(obj, param)Similar.
// 3.2 Medium method return, void method return null, basic number of type, type-based automatic box (eg, int-kai automatic conversion Integer).

Top surface static measurement test can be obtained. Top surface static surrogate result. Since the proxy can be used as a proxy, the main adjustments have been completed. Proxy.newProxyInstance (...) Operation and ʻInvocationHandler-like ʻinvoke-like methodical implementation. It is necessary to see the JDK, and when it is time to go, it is possible to measure it.

// env: JDK1.8 / IntelliJ IDEA 15 / macOS Majave
System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");

You can see the idea of IDEA.

#Motion generation surrogate position
...
|-- com/
| |--sun/
| | |--proxy/
| | | |--$Proxy0.class
...

Bottom surface decompilation $ Proxy0.class Post-partial decommissioning: Can be seen by proxy, proxy type and implementation completed Moveable interface. Main achievement Object type equals, hashCode sum toString Basic method Sum Moveable interface method move.


// ----- $Proxy0.class
public final class $Proxy0 extends Proxy implements Moveable {
    ...
    public $Proxy0(InvocationHandler var1) throws  { super(var1); }
    public final void move(Integer var1) throws  {
        try {
            super.h.invoke(this, m3, new Object[]{var1}); // 1 
        } ...
    }

    public final boolean equals(Object var1) throws  { ... }
    public final String toString() throws  { ... }
    public final int hashCode() throws  { ... }

    static {
        try {
            m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[]{Class.forName("java.lang.Object")});
            m3 = Class.forName("proxy.lizi.Moveable").getMethod("move", new Class[]{Class.forName("java.lang.Integer")});
            ...
        } ...
    }
}

Top surface sword (1 position) super.h Assistance manual InvocationHandler example, m3 can sequel sword detection move method. InvocationHandler for configuration proxy move actual implementation instance method. Subsided time diagram Easy description completed The above-mentioned dynamic proxy construction and sequence process: times.png

Note: Yu JDK source code approved and understood dynamic state proxy practical method: Java-like reflex mechanism + ASM (one-piece operation character 节 码 -like frame). Reflective control movable state classification and method, however, for the limit of the control and adjustment; ASM can be directly operated character byte code (.class text), and so on.

Dynamic proxy application example child

MyBatis

MyBatis's subsection superior endurance layered frame, other support standardized SQL, high-level projection beyond the history of existence. Use MyBatis Time General demand Photograph Mapper.xml Placement and interface XXXMapper.java, Nyoshita:

<!-- XXXMapper.xml -->
<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="tk.mybatis.simple.mapper.UserMapper">
    <select id="selectById" resultMap="userMap">
        SELECT * from sys_user where id = #{id}
    </select>
    <select id="selectAll" resultType="tk.mybatis.simple.model.SysUser"> 
    	select id,
		user_name userName
	from sys_user
    </select>
    ...
</mapper>

// ---- UserMapper.java
public interface UserMapper {
	/**
	 *Pass id 查 询 户
	 * 
	 * @param id
	 * @return
	 */
	SysUser selectById(Long id);
	
	/**
	 *User for possession of 查 询
	 * 
	 * @return
	 */
	List<SysUser> selectAll();
}

Mapper interface is depressed, and the interface is normally adjusted. This is the cause of MyBaits. Basic Principles Passing through XML Documental Arrangement Information Re-establishment Mapper Interface Definition Actually, the interface method.

Dynamic proxy for spring

Spring frame core policy IoC (Inversion of Control) sum AOP (Aspect Oriented Programming). Spring bean-like Dependency Injection (DI: Can Pass XML Method, Japanese Note-Oriented Method) and Aspect-Oriented Programming Method cglib (Code Generation Library) Principles Control Generation Completed Subclass Subclass, Subclass Subclass Possession Unrequited Final Method, Residential Technology Method Possessed Father's Method For adjustment, cross-cutting logic. cglib-like bottom layered ASM frame frame used.

Recommended Posts

Java Dynamic Proxy
Java
Java
Annotation instance is Dynamic Proxy
[Java] Proxy setting method when starting Java
Using proxy service with Java crawling
Java learning (0)
Studying Java ―― 3
[Java] array
Java protected
[Java] Annotation
Let's explain Dynamic Proxy as easily as possible
[Java] Module
Java array
Studying Java ―― 9
Java scratch scratch
Java tips, tips
Java methods
Java method
java (constructor)
Java array
[Java] ArrayDeque
java (override)
java (method)
Java string
java (array)
Java serialization
java beginner 4
JAVA paid
Studying Java ―― 4
Java (set)
java shellsort
[Java] compareTo
Studying Java -5
java reflexes
java (interface)
Java memorandum
☾ Java / Collection
Java array
Studying Java ―― 1
[Java] Polymorphism
Studying Java # 0
Java review
Java features
[Java] Inheritance
FastScanner Java
Java features
Proxy Pattern
Java memo
java (encapsulation)
Java inheritance
[Java] Overload
Java basics
Decompile Java
[Java] Annotation
java notes
java beginner
Java (add2)
JAVA (Map)
[java] interface
Java9 collection