A small example of achieving agent

zhaozj2021-02-12  136

I am very helpful to this example of implementing the database connection pool!

Firstly, it is generated in a interface. Java

Package proxytest;

Public interface cons {void close (); void open ();

Below is a CONSIMPL.JAVA for implementing CONS:

Package proxytest;

Public Class Consimpl Implements Cons {Public Void Close () {system.out.println ("Call CLOSE Method Implemented!"); ");

}

We now have to block the close () method! It is necessary to generate a proxy consPropy.java:

Package proxytest;

Import java.lang.reflect. *;

Public class consproxy imports invocationhandler {public consproxy (cons _cons) {this.cons = _cons;} public cons getcons () // Generate a proxy object! {Cons.newProxyInstance (Cons.getClass (). GetClassLoader (), cons. GetClass (); getInterface (); return cable1;} public object infhot (Object Proxy, Method M, Object [ ] args) throws throwable {Object obj = null; // Determine whether to call a Close method, if you call the Close method, call the other way you want to call! IF (close_method_name.equals)) Close (); else obj = m.invoke (cons, args); returnobj;} public void close () {system.out.println ("calling agent Close method! ");

Private cons cons = null; private final static string close_method_name = "close";

After generating a proxy, we can test, test code proxytest.java

Package proxytest;

Public class proxytest {public static void main (string args []) {cond = new consimpl (); consProxy proxy = new conspproxy (); cons (); // Get the agent CONS. CLOSE (); // This is there is no Agent's cons object! CONS1.CLOSE (); // This is an agent object}

}

Results of the:

Call the CLOSE method implemented by consimpl! Call the close method in the agent!

It's so simple, I hope to help everyone!

转载请注明原文地址:https://www.9cbs.com/read-7387.html

New Post(0)