Created
May 8, 2012 17:07
-
-
Save aJanuary/2637407 to your computer and use it in GitHub Desktop.
Quick way to automatically fix an object to a particular interface in Java.
This file contains hidden or 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
import java.lang.reflect.InvocationHandler; | |
import java.lang.reflect.Method; | |
import java.lang.reflect.Proxy; | |
public class InterfaceFixer { | |
@SuppressWarnings("unchecked") | |
public static <T> T fixToInterface(T object, Class<T> clazz) { | |
return (T) Proxy.newProxyInstance( | |
clazz.getClassLoader(), | |
new Class[] { clazz }, | |
new FixedInvocationHandler(object)); | |
} | |
private static class FixedInvocationHandler implements InvocationHandler { | |
Object obj; | |
public FixedInvocationHandler(Object obj) { | |
this.obj = obj; | |
} | |
@Override | |
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { | |
return method.invoke(obj, args); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Is there an existing library that does something like this that you can combine to Cloneable to easily create (non reflection safe) read-only copies of your objects by splitting it into a read and write interface?