Java Dynamic Proxies is the java answer for AOP programming . AOP is going to be another big thing like OOPS.
Java dynamic proxies works on the concept of interception . What it means is that at run time some handler would intercept the call to called object and invoke the methods on the object . This means you are detached from actual implementation . The same things happen in
EJB's . Infact whole
JBOSS is written using dynamic proxies .
Slightly confusing !!.
Here it goes how ..
Lets say you have an interface and some implementing objects for that interface. Now before actual call at run time to the methods you want to intercept the calls to the methods and provide some functionality like logging etc .
So you create a Proxy class that does that for you .
Here is a simple example ...
Interface
------------
public interface Nikhil {
public
String test();
public String test1();
}
Implementing Object
-----------------------
public class MyNikhil implements Nikhil {
public String test1(){
System.out.println("Hi Nikhil");
return "nikhil";
}
public String test(){
System.out.println("Hi Nikhil1");
return "nikhil1";
}
}
Proxy & Invocation Handler class
------------------------------------
import java.lang.ref.*;
import java.lang.reflect.InvocationHandler;
public class Test1 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MySalary mgrSalary = new ManagerSalary();
Nikhil myNikhil = new MyNikhil();
Object sal = (Object)java.lang.reflect.Proxy.newProxyInstance(
Salary.class.getClassLoader(),
new Class[] {Salary.class,Nikhil.class},
new Test1().new SalaryHandler( myNikhil ) ) ;
myNikhil.test();
myNikhil.test1();
Nikhil test= (Nikhil)sal;
test.test();
test.test1();
}
private class SalaryHandler implements InvocationHandler{
Object object;
public SalaryHandler(Object object1){
object = object1;
}
/** a generic, reflection-based secure invocation */
public Object invoke(Object target,
java.lang.reflect.Method method, Object[] arguments)
throws Throwable {
try{
// call framework and then reflect the app-logic
System.out.println("Method Name is "+method.getName());
return method.invoke(object,arguments);
} catch(java.lang.reflect.InvocationTargetException e) {
// reconvert nested application exceptions
throw e.getTargetException();
}
}
}//end of SalaryHandler class
}
The output of main method will be different .Here in this example Object sal is the proxy for the Nikhil Interface ..
Hope it helps .