动态代理Proxy对象在使用JSON的toJSONString时,里面的内容丢失,怎么处理
时间: 2023-05-18 10:06:41 浏览: 126
可以尝试在代理对象中重写toString方法,将代理对象转换为JSON字符串。具体实现可以参考以下代码:
public class ProxyHandler implements InvocationHandler {
private Object target;
public ProxyHandler(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = method.invoke(target, args);
if (method.getName().equals("toString")) {
return JSON.toJSONString(target);
}
return result;
}
}
然后在使用动态代理时,将ProxyHandler作为参数传入即可:
YourInterface yourInterface = (YourInterface) Proxy.newProxyInstance(
YourInterface.class.getClassLoader(),
new Class[]{YourInterface.class},
new ProxyHandler(yourObject)
);
当调用yourInterface.toString()时,将返回代理对象的JSON字符串。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)