Last active
February 20, 2017 09:54
-
-
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
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
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"; | |
} | |
} | |
} |
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
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