Skip to content

Instantly share code, notes, and snippets.

@aJanuary
Created May 8, 2012 17:07
Show Gist options
  • Save aJanuary/2637407 to your computer and use it in GitHub Desktop.
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.
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);
}
}
}
@aJanuary
Copy link
Author

aJanuary commented May 8, 2012

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?

interface List<T> { T get(int index); } // read-only interface
interface MutableList<T> extends List<T> { void append(T item); } // writeable interface

MutableList<T> list = new ArrayList<Integer>();
list.add(10); list.add(20); list.add(30);
List<T> frozenList = fixToInterface(list.clone(), IList.class);

((MutableList<Integer>) frozenList).add(10); // Throws class cast exception

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment