Recently in the development of a buckle, involving a large number of HTTP calls, a generic template is written, serialized, deserialized, and all HTTP calls are consolidated into the generic base class. public abstract class Wxcallbackhandler<c extends Weixinreturnparameter> implements CallbackHandler { private static final Org.slf4j.Logger log= Loggerfactory.getlogger (wxcallbackhandler.class); private static final String xml_tag= "XML"; protected Threadlocal<c> context=new threadlocal<c> () private static final Charset utf8_charset= Charset.forname ("Utf-8"); private XStream xstream; private static XStream wxcommonresultxstream; static {Wxcommonresultxstream = Nonamecoderwithcdatafacotry.instance (). Create (); Wxcommonresultxstream.autodetectannotations (boolean.true); Wxcommonresultxstream.alias (XML_TAG, Weixinxmlresult.class);} public Wxcallbackhandler () { xstream = Nonamecoderwithcdatafacotry.instance (). Create (); Xstream.autodetectannotations (boolean.true);//---------------------------------------------------------------- -The following is the get generic parameter-----------------------------Class curRent=this.getclass (); while (! WxCallbackHandler.class.equals (Current.getsuperclass ())) {Current=current.getsuperclass ();/* In order to handle multilevel inheritance */}type Gentype = Current.getgenericsuperclass (); Type[] params = ((Parameterizedtype) gentype). Getactualtypearguments ();//========================================= = = = Get generic parameter end =======================xstream.alias (Xml_tag, (Class) params[0]);} private void parser (callbackparameter parameter) {ServletInputStream Inputstream=null;try { Inputstream=parameter.getrequest (). getInputStream (); String XmlText = ioutils.tostring (InputStream, Utf8_charset), if (log.isinfoenabled ()) {Log.info ("callback request message as follows {} {}", Parameter.tostring (), xmlText);} Context.set ((C) Xstream.fromxml (XmlText)); catch (Throwable throwable) {log.error (Throwable.getmessage (), throwable), throw new RuntimeException (Throwable); }finally {ioutils.closequietly (InputStream);}} @Overridepublic void execute (callbackparameter parameter) {parser (parameter); Weixinxmlresult result=new Weixinxmlresult (DoEXecute ()), if (log.isinfoenabled ()) {Log.info ("Reply call results as follows {}", Gsonutils.defaultgson (). ToJson (Result));} PrintWriter Writer=null;try {HttpServletResponse response = Parameter.getresponse (); writer = Response.getwriter (); Writer.print (Wxcommonresultxstream.toxml (Result)); Writer.flush ();} catch (Throwable throwable) {log.error (Throwable.getmessage (), throwable); throw new RuntimeException (Throwable);} Finally {ioutils.closequietly (writer);} } public Abstract Boolean Doexecute (); }
Java gets the generic parameters passed by subclasses in the generic base class