Created
November 19, 2015 11:17
-
-
Save unix-junkie/b9481245904892f07780 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
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