Skip to content

Instantly share code, notes, and snippets.

@raulraja
Created October 22, 2012 13:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raulraja/3931432 to your computer and use it in GitHub Desktop.
Save raulraja/3931432 to your computer and use it in GitHub Desktop.
Sample Java Proxy
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