Created
October 22, 2012 13:09
-
-
Save raulraja/3931432 to your computer and use it in GitHub Desktop.
Sample Java Proxy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface PersistenceService { | |
Object save(Object obj); | |
} | |
class DatabasePersistenceService implements PersistenceService { | |
@Override | |
public Object save(Object obj) { | |
//save to the database | |
return null; | |
} | |
} | |
public class PersistenceServiceProxy implements InvocationHandler { | |
private Object obj; | |
public static Object newInstance(Object obj) { | |
return java.lang.reflect.Proxy.newProxyInstance( | |
obj.getClass().getClassLoader(), | |
obj.getClass().getInterfaces(), | |
new PersistenceServiceProxy(obj)); | |
} | |
private PersistenceServiceProxy(Object obj) { | |
this.obj = obj; | |
} | |
public Object invoke(Object proxy, Method m, Object[] args) | |
throws Throwable { | |
Object result; | |
try { | |
System.out.println("before method " + m.getName()); | |
result = m.invoke(obj, args); | |
} catch (InvocationTargetException e) { | |
throw e.getTargetException(); | |
} catch (Exception e) { | |
throw new RuntimeException("unexpected invocation exception: " + | |
e.getMessage()); | |
} finally { | |
System.out.println("after method " + m.getName()); | |
} | |
return result; | |
} | |
public static void main(String... args) { | |
PersistenceService proxy = (PersistenceService) PersistenceServiceProxy.newInstance(new DatabasePersistenceService()); | |
proxy.save(new Object()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment