Skip to content

Instantly share code, notes, and snippets.

@unix-junkie
Created November 19, 2015 11:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save unix-junkie/b9481245904892f07780 to your computer and use it in GitHub Desktop.
Save unix-junkie/b9481245904892f07780 to your computer and use it in GitHub Desktop.
package com.example;
import static java.lang.Thread.currentThread;
import static java.lang.reflect.Proxy.newProxyInstance;
interface Duck {
void walk();
void quack();
/**
* Not implemented by {@link Elephant}.
*/
void doDucklikeThings();
}
interface Elephant {
void walk();
void quack();
}
final class ElephantImpl implements Elephant {
@Override
public void walk() {
System.out.println("I'm an elephant, and I can walk");
}
@Override
public void quack() {
System.out.println("I'm a quacking elephant");
}
}
class Main {
public static void main(final String[] args) {
final Elephant elephant = new ElephantImpl();
final Duck duck = (Duck) newProxyInstance(currentThread().getContextClassLoader(),
new Class[] {Elephant.class, Duck.class /* order matters */},
(proxy, method, methodArgs) -> method.invoke(elephant, methodArgs));
duck.walk();
duck.quack();
if (false) {
duck.doDucklikeThings(); // will throw an IAE
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment