通过动态代理,不直接调用对象,而是通过代理proxy调用对象的方法
package com.zg.myssm.service;
/**
* @Auther: Zg
* @Date: 2022/11/28 - 11 - 28 - 23:43
* @Description: com.zg.myssm.service
* @version: 1.0
*/
public interface A {
void t1();
void t2();
void t3(String s1,String s2);
}
package com.zg.myssm.service.impl;
import com.zg.myssm.service.A;
/**
* @Auther: Zg
* @Date: 2022/11/28 - 11 - 28 - 23:44
* @Description: com.zg.myssm.service.impl
* @version: 1.0
*/
public class A1 implements A {
@Override
public void t1() {
System.out.println("t1");
}
@Override
public void t2() {
System.out.println("t2");
}
@Override
public void t3(String s1, String s2) {
System.out.println("t3"+s1+","+s2);
}
}
测试:
@Test
public void Test21(){
/**
classloader:boot,ext,app Test.class.getClassLoader() 类加载到虚拟机
Class[] interfaceClass
InvocationHandler: 接口,自定义实现类
*/
A1 a1 = new A1();
A a = (A)Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
new Class[]{A.class}, (proxy, method, args) -> {
method.invoke(a1,args);
System.out.println("=====");
System.out.println(Arrays.toString(args));
return null;
});
a.t1();
a.t2();
a.t3("sb","sbb");
/**
结果:
t1
=====
null
t2
=====
null
t3sb,sbb
=====
[sb, sbb]
*/
// A a = (A)Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
// new Class[]{A.class}, new InvocationHandler() {
// @Override
// public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// method.invoke(a1,args);
// System.out.println("=====");
// System.out.println(Arrays.toString(args));
// return null;
// }
// });