Skip to content

Instantly share code, notes, and snippets.

@nathansgreen
Last active June 16, 2022 19:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nathansgreen/11084652 to your computer and use it in GitHub Desktop.
Save nathansgreen/11084652 to your computer and use it in GitHub Desktop.
java.lang.reflect.Proxy over Annotation
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