Skip to content

Instantly share code, notes, and snippets.

@yinonavraham
Last active February 20, 2017 09:54
Show Gist options
  • Save yinonavraham/b9daceda78da36fc24445854a654c18c to your computer and use it in GitHub Desktop.
Save yinonavraham/b9daceda78da36fc24445854a654c18c to your computer and use it in GitHub Desktop.
Part of the following post in orange-coding.blogspot.com: Enhancing (extending) a class using dynamic proxy classes in Java
public abstract class ABFactory {
private ABFactory() { /* prevent instantiation */ }
public static AB createAB(A a) {
B b = new BImpl(a);
return (AB) Proxy.newProxyInstance(a.getClass().getClassLoader(),
new Class[]{AB.class}, (proxy, method, args) -> {
Class<?>[] declaringClassInterfaces = method.getDeclaringClass().getInterfaces();
List<Class<?>> interfaces = new ArrayList<>(Arrays.asList(declaringClassInterfaces));
interfaces.add(method.getDeclaringClass());
if (interfaces.contains(A.class)) {
return method.invoke(a, args);
} else if (interfaces.contains(B.class)) {
return method.invoke(b, args);
} else {
throw new NoSuchMethodException("Could not find proxied method: " +
method.toGenericString());
}
});
}
private static class BImpl implements B {
private final A a;
private BImpl(A a) {
this.a = a;
}
@Override
public String bar() {
return a.foo() + "bar";
}
}
}
A a = new AImpl();
...
AB ab = ABFactory.create(a);
System.out.println(ab.foo()); //prints "foo"
System.out.println(ab.bar()); //prints "foo & bar"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment