Created
September 22, 2011 12:49
-
-
Save mathieuancelin/1234687 to your computer and use it in GitHub Desktop.
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
import javassist.util.proxy.MethodHandler; | |
import javassist.util.proxy.ProxyFactory; | |
import org.osgi.framework.Bundle; | |
public class MyProxyFactory extends ProxyFactory { | |
private final Bundle bundle; | |
public MyProxyFactory(Bundle bundle) { | |
this.bundle = bundle; | |
} | |
protected ClassLoader getClassLoader0() { | |
return new BridgeClassLoader(bundle, getClass().getClassLoader()); | |
} | |
private static class BridgeClassLoader extends ClassLoader { | |
private final Bundle delegate; | |
private final ClassLoader infra; | |
public BridgeClassLoader(Bundle delegate, ClassLoader infraClassLoader) { | |
this.delegate = delegate; | |
this.infra = infraClassLoader; | |
} | |
@Override | |
public Class<?> loadClass(String name) throws ClassNotFoundException { | |
Class<?> loadedClass = null; | |
try { | |
loadedClass = delegate.loadClass(name); | |
} catch (ClassNotFoundException cnfe) { | |
loadedClass = infra.loadClass(name); | |
} | |
return loadedClass; | |
} | |
} | |
public static void test() { | |
ProxyFactory f = new MyProxyFactory(getMyBundle()); | |
f.setSuperclass(Foo.class); | |
f.setFilter(new MethodFilter() { | |
public boolean isHandled(Method m) { | |
// ignore finalize() | |
return !m.getName().equals("finalize"); | |
} | |
}); | |
Class c = f.createClass(); | |
MethodHandler mi = new MethodHandler() { | |
public Object invoke(Object self, Method m, Method proceed, | |
Object[] args) throws Throwable { | |
System.out.println("Name: " + m.getName()); | |
return proceed.invoke(self, args); // execute the original method. | |
} | |
}; | |
Foo foo = (Foo) c.newInstance(); | |
((ProxyObject) foo).setHandler(mi); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment