Public interface someclass {
Public abstract void somemethod ();
Public abstract void someothermethod (final string text );
}
Public class someclassimpl implements someclass {
Private string username;
Public someclassimpl (final string username ){
This. Username = username;
}
Public void somemethod (){
System. Out. println (this. username );
}
Public void someothermethod (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 implements invocationhandler {
/* Whatever object, you can pass one in */
Private final object impl;
Private int invocationcount = 0;
/* Constructor */
Public methodcountinghandler (final object impl ){
This. impl = impl;
}
/* Export the invocation count */
Public int getinvocationcount (){
Return invocationcount;
}
/* 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. getdynamicsomeclassproxy ();
Proxy. somemethod ();
Proxy. someothermethod ("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 Dynamic proxy only supports interface-Based Method interception. This example is extracted from the book "Hardcore Java.