Last active
June 10, 2019 23:57
-
-
Save netoht/71b77495e5640e160bb5 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
import static java.lang.annotation.ElementType.METHOD; | |
import static java.lang.annotation.RetentionPolicy.RUNTIME; | |
import java.lang.annotation.Retention; | |
import java.lang.annotation.Target; | |
import java.lang.reflect.Method; | |
import java.lang.reflect.Proxy; | |
import java.util.HashMap; | |
import java.util.Map; | |
@Target(METHOD) | |
@Retention(RUNTIME) | |
@interface MyAnnotation { | |
String value(); | |
} | |
interface MyInterface { | |
@MyAnnotation("key1") | |
String getSomeValue1(); | |
@MyAnnotation("key2") | |
String getSomeValue2(); | |
} | |
class MyConfigFactory implements java.lang.reflect.InvocationHandler { | |
public static <T> T get(Class<?> clazz) { | |
MyConfigFactory config = new MyConfigFactory(); | |
return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class<?>[] { clazz }, config); | |
} | |
Map<String, String> store = new HashMap<String, String>() { | |
{ | |
put("key1", "myValue1"); | |
put("key2", "myValue2"); | |
put("key3", "myValue3"); | |
} | |
}; | |
@Override | |
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { | |
MyAnnotation annontation = method.getAnnotation(MyAnnotation.class); | |
if (annontation != null) { | |
String key = annontation.value(); | |
if (store.containsKey(key)) { | |
return store.get(key); | |
} | |
return null; | |
} | |
return method.invoke(this, args); | |
} | |
} | |
public class ExampleDynamicProxy { | |
public static void main(String[] args) { | |
MyInterface myImplements = MyConfigFactory.get(MyInterface.class); | |
System.out.println(myImplements.getSomeValue1()); | |
System.out.println(myImplements.getSomeValue2()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment