例子 。
package com.proxytest;
import java.lang.reflect.Method;
public interface Advice {
public void beforeMethod(Object arg0, Method arg1, Object[] arg2);
public void afterMethod(Object arg0, Method arg1, Object[] arg2);
}
package com.proxytest;
import java.lang.reflect.Method;
public class LogAdvice implements Advice{
@Override
public void beforeMethod(Object arg0, Method arg1, Object[] arg2) {
System.out.println("before " + arg0.getClass() + " " + arg1.getName() );
}
@Override
public void afterMethod(Object arg0, Method arg1, Object[] arg2) {
System.out.println("end" + arg0.getClass() + " " + arg1.getName() );
}
}
package com.proxytest;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class BeanFactory {
private Properties prop = new Properties();
public BeanFactory(InputStream in)
{
try {
prop.load(in);
} catch (IOException e) {
e.printStackTrace();
}
}
public Object getBean(String name)
{
String className = prop.getProperty(name);
Object bean = null;
try {
bean = Class.forName(className).newInstance();
if(bean instanceof ProxyFactoryBean)
{
Advice advice = (Advice) Class.forName(prop.getProperty(name+".advice")).newInstance();
Object target = Class.forName(prop.getProperty(name+".target")).newInstance();
ProxyFactoryBean pfb = new ProxyFactoryBean();
pfb.setAdvice(advice);
pfb.setTarget(target);
bean = pfb.getProxy();
}
} catch (Exception e) {
e.printStackTrace();
}
return bean;
}
}
package com.proxytest;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyFactoryBean {
public Advice getAdvice() {
return advice;
}
public void setAdvice(Advice advice) {
this.advice = advice;
}
public Object getTarget() {
return target;
}
public void setTarget(Object target) {
this.target = target;
}
private Advice advice;
private Object target;
public Object getProxy() {
Object object = Proxy.newProxyInstance(target.getClass()
.getClassLoader(), target.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object arg0, Method arg1, Object[] arg2)
throws Throwable {
advice.beforeMethod(arg0, arg1, arg2);
Object retVal = arg1.invoke(target, arg2);
advice.afterMethod(arg0, arg1, arg2);
return retVal;
}
});
return object;
}
}
config.properties
#xxx=java.util.ArrayList
xxx=com.proxytest.ProxyFactoryBean
xxx.advice = com.proxytest.LogAdvice
xxx.target = java.util.ArrayList
package com.proxytest;
import java.io.InputStream;
import java.util.Collection;
public class Test {
public static void main(String[] args) {
InputStream in = Test.class.getResourceAsStream("config.properties");
BeanFactory bf = new BeanFactory(in);
Collection c = (Collection) bf.getBean("xxx");
c.add("2");
System.out.println(c.getClass() + " " + c);
}
}