Last active
November 26, 2024 13:24
-
-
Save nathansgreen/11084652 to your computer and use it in GitHub Desktop.
java.lang.reflect.Proxy over Annotation
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 java.lang.annotation.Retention; | |
import java.lang.annotation.RetentionPolicy; | |
import java.lang.reflect.InvocationHandler; | |
import java.lang.reflect.Method; | |
import java.lang.reflect.Proxy; | |
import java.util.HashMap; | |
import java.util.Map; | |
import org.junit.Assert; | |
import org.junit.Test; | |
public class ProxyTest { | |
@Retention(RetentionPolicy.RUNTIME) | |
static @interface Annotation { | |
String message(); | |
long value(); | |
} | |
static class Handler implements InvocationHandler { | |
private final Map behavior; | |
Handler(Map behavior) { | |
this.behavior = behavior; | |
} | |
@Override | |
public Object invoke(Object proxy, Method method, Object[] args) { | |
return behavior.get(method.getName()); | |
} | |
} | |
@Test | |
@Annotation(value = 10L, message = "Goodbye, World") | |
public void testProxy() throws Exception { | |
final Map map = new HashMap(1); | |
map.put("message", "Hello World!"); | |
map.put("value", 10L); | |
final Annotation min = (Annotation) Proxy.newProxyInstance( | |
getClass().getClassLoader(), | |
new Class[] {Annotation.class}, | |
new Handler(map)); | |
final Annotation staticMin = getClass() | |
.getMethod("testProxy").getAnnotation(Annotation.class); | |
System.out.println(min.message()); // Hello World! | |
System.out.println(staticMin.message()); | |
Assert.assertEquals(min.value(), staticMin.value()); // 10L | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment