java – 在这个用例中使用Reflection来解决我不允许修复的设计问
发布时间:2020-12-15 04:46:08 所属栏目:Java 来源:网络整理
导读:以下用例是否被视为反映的合理性? 从XSD生成的一堆类(当前在项目中有数百个)代表各种响应. 所有这些响应都包括常见的响应数据结构,而不是扩展它. 当发生超时等事件时,我只需要将单个String设置为特定值. 如果这些类扩展了常见的响应结构,我可以始终设置此响
以下用例是否被视为反映的合理性?
从XSD生成的一堆类(当前在项目中有数百个)代表各种响应. 所有这些响应都包括常见的响应数据结构,而不是扩展它. 当发生超时等事件时,我只需要将单个String设置为特定值. 如果这些类扩展了常见的响应结构,我可以始终设置此响应代码而不进行反射,但事实并非如此. 因此,我为我的服务编写了一个简单的实用程序,它使用反射获取String字段的setter方法并使用预定义的值调用它. protected T handleTimeout(Class<T> timeoutClass) { try { T timeout = timeoutClass.newInstance(); Method setCode = timeoutClass.getDeclaredMethod(SET_RESPONSE_CODE,String.class); setCode.invoke(timeout,Response.TIMEOUT.getCode()); return timeout; } catch (InstantiationException | IllegalAccessException | SecurityException | NoSuchMethodException | IllegalArgumentException | InvocationTargetException e) { e.printStackTrace(); throw new RuntimeException("Response classes must have field: "code" !"); } } 相关事实: >这个setter方法永远不会改变,因为它需要返工数百个接口 有人可能会指出,如果我错过了一些陷阱,或者是否存在可以实现相同结果的反射解决方案? 编辑:我根本无权在XSD上进行任何更改,因此任何解决方案都必须在本地完成.序列化这些对象应该没有问题,因为它们在组件之间共享. 解决方法
我尝试了一种替代解决方案,用于从xml架构生成类,而不是反射.
您可以为xjc提供如下自定义绑定: <?xml version="1.0" encoding="UTF-8"?> <bindings xmlns="http://java.sun.com/xml/ns/jaxb" xmlns:xsi="http://www.w3.org/2000/10/XMLSchema-instance" xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc" xsi:schemaLocation="http://java.sun.com/xml/ns/jaxb http://java.sun.com/xml/ns/jaxb/bindingschema_2_0.xsd" version="2.1"> <globalBindings> <xjc:superClass name="XmlSuperClass" /> </globalBindings> </bindings> 并实现你像这样的XmlSuperClass: @XmlTransient // to prevent that the shadowed responseCode be marshalled public class XmlSuperClass { private String responseCode; // this will be shadowed public String getResponseCode() { // this will be overridden return responseCode; } public void setResponseCode(String value) { //overridden too this.responseCode = value; } } 像这样调用xjc: xjc -extension -b <yourbinding.xjb> -cp <XmlSuperClass> <xmlschemas.xsd...> 将生成绑定类,如: @XmlRootElement(name = "whatever") public class Whatever extends XmlSuperClass { @XmlElement(required = true) protected String responseCode; // shadowing public void setResponseCode(String...) //overriding } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |