Created
May 27, 2011 15:50
-
-
Save karanmalhi/995537 to your computer and use it in GitHub Desktop.
Simple example on how to create proxies
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
package com.learnquest; | |
import java.lang.reflect.InvocationHandler; | |
import java.lang.reflect.Method; | |
import java.lang.reflect.Proxy; | |
import java.util.ArrayList; | |
import java.util.List; | |
import java.util.logging.Logger; | |
public class ProxyTest { | |
public static void main(String[] args) throws Exception { | |
ICalculator calc = (ICalculator) ObjectFactory.create(Calculator.class); | |
System.out.println(calc.getClass().getName()); | |
int result = calc.add(100, 200); | |
List names = (List) ObjectFactory.create(ArrayList.class); | |
names.add("alice"); | |
} | |
} | |
class ObjectFactory { | |
public static Object create(Class clazz) throws Exception { | |
Object targetObject = clazz.newInstance(); | |
Object proxyInstance = Proxy.newProxyInstance(clazz.getClassLoader(), | |
clazz.getInterfaces(), new LoggingAspect(targetObject)); | |
return proxyInstance; | |
// return clazz.newInstance(); | |
} | |
} | |
class LoggingAspect implements InvocationHandler { | |
private Logger logger; | |
private Object target; | |
public LoggingAspect(Object target) { | |
this.target = target; | |
logger = Logger.getLogger(target.getClass().getName()); | |
} | |
@Override | |
public Object invoke(Object proxy, Method method, Object[] args) | |
throws Throwable { | |
StringBuffer buff = new StringBuffer(); | |
buff.append(method.getName() + " is called with arguments "); | |
if (args != null) { | |
for (Object object : args) { | |
buff.append(object).append(" , "); | |
} | |
} | |
logger.info(buff.toString()); | |
// call the target object | |
Object result = method.invoke(target, args); | |
logger.info("method " + method.getName() + " returned a result of " | |
+ result); | |
return result; | |
} | |
} | |
interface ICalculator { | |
public abstract int add(int x, int y); | |
} | |
class Calculator implements ICalculator { | |
@Override | |
public int add(int x, int y) { | |
return x + y; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment