Java dynamic proxy example

zhaozj2021-02-16  81

Public interface someclass {

Public abstract void someMethod ();

Public Abstract Void Someharmthod (Final String Text);

Public Class SomeClassImpl Implements SomeClass {

PRIVATE STRING UserName;

Public String UserName {this.username = username;}

Public void someMethod () {system.out.println (this.username);

Public void Someharmthod (Final String Text) {system.out.println (text);}}

Import java.lang.reflect.invocationhandler; import java.lang.reflect.InvocationTargeTexception; import java.lang.reflect.Method;

Public class methodcountinghandler imports invocationhandler {

/ * Whatver Object, You CAN pass one in * / private finAl Object IMPL;

Private int invocationcount = 0;

/ * Constructor * / public methodcounting, {this.impl = IMPL;}

/ * export the invocation count * / public int getInvocationcount () {return infocationcount;}

/ * Implements the interface function of InvocationHandler * / public Object invoke (Object proxy, Method meth, Object [] args) throws Throwable {try {this.invocationCount ; Object result = meth.invoke (impl, args); return result;} Catch (Final InvocationTargeTexception EX) {throw ex.gettargetexception ();}}}

Import java.lang.reflect.invocationhandler; import java.lang.reflect.Proxy;

Public class someclassfactory {

Public static final someclass getDynamicsomeclassproxy () {

/ * GET A Implement Instance of SomeClass * / SomeClassImpl Impl = New SomeClassImpl (System.getProperty ("User.Name"));

IF (! (iMPL InstanceOf SomeClass) Return NULL;

/ * Construct a invocation handler with the impl instance * / InvocationHandler handler = new MethodCountingHandler (impl); / * get the class info, and the class loader used by this factory * / Class [] interfaces = new Class [] {SomeClass. Class}; ClassLoader Loader = SomeClassFactory.class.getClassLoader ();

/ * * Install the handler for all implementations of this interface in this class loader * and return the proxy instance which accords to SomeClass interface * / SomeClass proxy = (SomeClass) Proxy.newProxyInstance (loader, interfaces, handler).;

Return Proxy;

}

Import java.lang.reflect.invocationhandler; import java.lang.reflect.Proxy;

Public class demodynamicproxy {

Public Static Final Void Main (Final String [] args) {

SomeClass Proxy = SomeClassFactory.getDynamicsMeclassProxy ();

Proxy.SOMEMETHOD ();

Proxy.SOMETHERMETHOD ("Our Proxy Works!");

/ * get the handler associated with this proxy instance * / invocationhandler handler = proxy.getinvocationHandler (Proxy);

IF (Handler InstanceOf MethodCountingHandler) {System.out.Println ((MethodCountingHandler) Handler .getinvocationCount ());}}

}

Java's dynamic proxy only supports Interface-based Method Interception. This example is taken from the "Hardcore Java" book.

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

New Post(0)