首页 技术 正文
技术 2022年11月8日
0 收藏 461 点赞 1,205 浏览 1690 个字

JAVA的动态代理,在MYBATIS中应用的很广,其核心就是写一个interface,但不写实现类,然后用动态代理来实例化并执行这个interface中的方法,话不多说,来看一个实现的例子:

1.先定义一个接口:

public interface TestProxy {String hello();}

2.虽然不写实现类,但我们仍然希望在执行这个hello()方法时,能输出我们想要输出的内容,比如我把希望要输出的内容放在一个属性文件中:

hello=world

我希望在调用hello方法时,输出world,接下来得解析这个属性文件:

public class PropertiesHandler {private static Properties p = new Properties();static{
try {
InputStream in = new FileInputStream(new File("src/test.properties"));
p.load(in);
in.close();
} catch (IOException e) {
throw new RuntimeException("test.properties load error!");
}
}public static String getProperty(String key){
try{
return p.getProperty(key, null);
}catch(Exception e){
e.printStackTrace();
}
return "";
}}

3.解析完后,我们再写一个动态代理类:

public class ProxyImp<T> implements InvocationHandler{private Class<T> proxyMethod;public ProxyImp(Class<T> proxyMethod) {
this.proxyMethod = proxyMethod;
}@Override
public Object invoke(Object proxy, Method method, Object[] args)throws Throwable {
String value = PropertiesHandler.getProperty(method.getName());
System.out.println(value);
return null;
}}

其原理就是在调用接口类方法时,动态代理类都会去执行这个invoke方法,以达到执行的目的,可以看到,在invoke方法里,我们把hello方法在属性文件中对应的值给取出来了,并输出。

4.接下来就是再封装一个代理工厂类来产生这个接口的一个实例:

public class ProxyImpFactory{@SuppressWarnings("unchecked")
public static <T> T newInstance(Class<T> methodInterface) {
final ProxyImp<T> proxyImp = new ProxyImp<T>(methodInterface);
return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
new Class[]{methodInterface},
proxyImp);
}}

可以从上面的代码中看出这个代理类会自动的生成一个接口实现类的实例。

5.接下来就是真正的调用了:

public static void main(String[] args) {
TestProxy tp = ProxyImpFactory.newInstance(TestProxy.class);
tp.hello();
}

输出就是:world.

6.动态代理在自动化中的作用:

 自动化中,当把元素对象用外部文件,把数据文件用外部文件时,都可以用这种方式来进行封装,其在自动化测试中最大的作用,我想就是利用在封装关键字上了,把关键字与具体的方法对应起来,就可以用这样的方式。

 至于具体的关键字的实现,我想得靠大家自已了,有兴趣的可以与我讨论!

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,110
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,584
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,431
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,202
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,837
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,920