------- <a href="http://www.itheima.com" target="blank">android培训</a>
代码演示:
//框架测试类
package com.itheima.aopframework;
import java.io.InputStream;
public class AopFrameworkTest {
public static void main(String[] args)throws Exception{
// TODO Auto-generated method stub
InputStream is = AopFrameworkTest.class.getResourceAsStream("config.properies");
Object obj = new BeanFactory(is).getBean("xxx");
System.out.println(obj.getClass().getName());
}
}
//判断是否是 ProxyFactroyBean类
package com.itheima.aopframework;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import com.itheima.Adivce;
public class BeanFactory {
Properties property = new Properties();
public BeanFactory(InputStream is){
try {
property.load(is);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Object getBean(String name){
String className = property.getProperty(name);
//通过反射创建类
Object bean = null;
try {
Class clazz = Class.forName(className);
bean = clazz.newInstance();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//判断是否是 ProxyFactroyBean类
if(bean instanceof ProxyFactoryBean){
Object proxy = null;
ProxyFactoryBean proxyFactoryBean = (ProxyFactoryBean)bean;
try {
Adivce adivce = (Adivce)Class.forName(property.getProperty(name + ".adivce")).newInstance();
Object target = Class.forName(property.getProperty(name + ".target")).newInstance();
proxyFactoryBean.setAdivce(adivce);
proxyFactoryBean.setTarget(target);
proxy = proxyFactoryBean.getProxy();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return proxy;
}
return bean;
}
}
//通过代理动态生成类
package com.itheima.aopframework;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import com.itheima.Adivce;
public class ProxyFactoryBean {
private Adivce adivce;
public Adivce getAdivce() {
return adivce;
}
public void setAdivce(Adivce adivce) {
this.adivce = adivce;
}
public Object getTarget() {
return target;
}
public void setTarget(Object target) {
this.target = target;
}
private Object target;
public Object getProxy() {
Object proxy2 = (Object)Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
adivce.startTime(method);
Object obj = method.invoke(target, args);
adivce.endTime(method);
return obj;
}
});
return proxy2;
}
}
<a href="http://www.itheima.com" target="blank">java培训</a>、期待与您交流! ----------