接口类:
public interface HelloService {
String sayHello(String name);
}
实现类:
public class HelloServiceImpl implements HelloService{
@Override
public String sayHello(String name) {
return "你好," + name;
}
}
客户端client:
public static void main(String[] args) {
HelloService helloService = new HelloServiceImpl();
HelloService aa = (HelloService) Proxy.newProxyInstance(HelloServiceImpl.class.getClassLoader(), HelloServiceImpl.class.getInterfaces(), new InvocationHandler() {
/**
* Object proxy:被代理对象的引用,系统会自动创建被代理对象的一个映射
* Method method:被代理对象的方法
* @param args
* Object[] args:被代理对象方法的参数
* 返回值是被代理对象执行后的返回值
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//被代理对象方法的执行,并获得返回值
Object result = method.invoke(helloService, args);
return result;
}
});
String result = aa.sayHello("ss");
System.out.println("result:" + result);
}
标签:args,String,JDK,Object,代理,result,动态,public,HelloService
From: https://blog.51cto.com/u_11315052/8909338