Last active
August 29, 2015 14:17
-
-
Save morgotth/6a93e0fc5071c968382c to your computer and use it in GitHub Desktop.
Avoid wrapper instanciation hell with 2 functions and 1 interface !
This file contains hidden or 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
$ javac WrapperTest.java | |
$ java WrapperTest | |
I'm a developer. Explicit is better than implicit ! Keep it KISS. |
This file contains hidden or 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 class WrapperTest { | |
public static void main(String[] args) throws ReflectiveOperationException { | |
Developer myProfile = wrap(MainDeveloper.class, PythonDeveloper.class, UnixDeveloper.class); | |
System.out.println(myProfile.develop()); | |
} | |
public static <T> T wrap(Class<T> t, Class... classes) throws ReflectiveOperationException, ClassCastException { | |
return wrap(t.newInstance(), classes); | |
} | |
@SuppressWarnings("unchecked") | |
public static <T> T wrap(T t, Class... classes) throws ReflectiveOperationException, ClassCastException { | |
if (classes.length == 0) return t; | |
Object temp; | |
Wrapper<T> newRet; | |
Wrapper<T> ret = (Wrapper<T>) classes[0].newInstance(); | |
ret.wrap(t); | |
for (int i = 1; i < classes.length; i++) { | |
temp = classes[i].newInstance(); | |
newRet = (Wrapper<T>) temp; | |
newRet.wrap((T) ret); | |
ret = newRet; | |
} | |
return (T) ret; | |
} | |
public static interface Wrapper<T> { | |
void wrap(T t); | |
} | |
public static interface Developer { | |
String develop(); | |
} | |
public static class MainDeveloper implements Developer { | |
@Override | |
public String develop() { | |
return "I'm a developer."; | |
} | |
} | |
public static class PythonDeveloper implements Developer, Wrapper<Developer> { | |
private Developer developer; | |
@Override | |
public void wrap(Developer developer) { | |
this.developer = developer; | |
} | |
@Override | |
public String develop() { | |
return developer.develop() + " Explicit is better than implicit !"; | |
} | |
} | |
public static class UnixDeveloper implements Developer, Wrapper<Developer> { | |
private Developer developer; | |
@Override | |
public void wrap(Developer developer) { | |
this.developer = developer; | |
} | |
@Override | |
public String develop() { | |
return developer.develop() + " Keep it KISS."; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment