Created
July 19, 2012 03:31
-
-
Save hpcx82/3140565 to your computer and use it in GitHub Desktop.
Test java's dynamic proxy class - to avoid boilplate wrapper code for all classes
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
package baiyanhuang; | |
import java.lang.reflect.InvocationHandler; | |
import java.lang.reflect.Method; | |
import java.lang.reflect.Proxy; | |
import java.util.Arrays; | |
import java.util.Random; | |
/** | |
* Learn Java's dynamic proxy (in reflection) | |
* It mainly use the reflection classes: InvocationHandler; Method; Proxy | |
*/ | |
public class ProxyTest { | |
public static void main(String[] args) { | |
Object[] elements = new Object[1000]; | |
// fill elements with proxies for the integers 1 ... 1000 | |
for (int i = 0; i < elements.length; i++) { | |
Integer value = i + 1; | |
Class[] interfaces = value.getClass().getInterfaces(); | |
InvocationHandler handler = new TraceHandler(value); | |
// Generate a proxy class on the fly that implement the "interfaces" using "handler", while the "handler" | |
// is actually calling the real object's method, adding some extra functionalities, say, logging. | |
Object proxy = Proxy.newProxyInstance(null, interfaces, handler); | |
elements[i] = proxy; | |
} | |
// construct a random integer | |
Integer key = new Random().nextInt(elements.length) + 1; | |
// search for the key | |
int result = Arrays.binarySearch(elements, key); | |
// print match if found | |
if (result >= 0) | |
System.out.println(elements[result]); | |
} | |
} | |
/** | |
* An invocation handler that prints out the method name and parameters, then invokes the original method | |
*/ | |
class TraceHandler implements InvocationHandler { | |
public TraceHandler(Object t) { | |
target = t; | |
} | |
// This function is called by the dynamically generated proxy class | |
public Object invoke(Object proxy, Method m, Object[] args) throws Throwable { | |
// print implicit argument | |
System.out.print(target); | |
// print method name | |
System.out.print("." + m.getName() + "("); | |
// print explicit arguments | |
if (args != null) { | |
for (int i = 0; i < args.length; i++) { | |
System.out.print(args[i]); | |
if (i < args.length - 1) | |
System.out.print(", "); | |
} | |
} | |
System.out.println(")"); | |
// invoke actual method | |
// return new Integer("123"); | |
return m.invoke(target, args); | |
} | |
private Object target; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment