Application of reflection in micro-channel public platform in

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/zhupanlinch/article/details/102693887

1, development background

When the development of micro-channel public number, we will go to resolve micro-channel message, and then do the corresponding operation according to the different message types. The following is a section of micro-channel message body:

<xml>

<ToUserName><![CDATA[toUser]]></ToUserName>

<FromUserName><![CDATA[fromUser]]></FromUserName>

<CreateTime>1348831860</CreateTime>

<MsgType><![CDATA[MsgType]]></MsgType>

<MsgId>1234567890123456</MsgId>

</xml>

MsgType here are eight kinds, namely, text, event. So many message types, how to do it? if ... else, switch? can handle, it seems It's too simple.

 

So the question came, and event news event. Are concerned about the news, take off, upload location, and custom menus. See message body:

<xml>

<ToUserName><![CDATA[toUser]]></ToUserName>

<FromUserName><![CDATA[FromUser]]></FromUserName>

<CreateTime>123456789</CreateTime>

<MsgType><![CDATA[event]]></MsgType>

<Event><![CDATA[subscribe]]></Event>

</xml>

Event messages are event types, specific event (click on the different buttons) corresponds to an Event, custom menu, when the Event that there are N planted. If you are used to write branch structure, it is a little embarrassing. So, in order to solve this embarrassing, following the introduction of a concept - reflection.

 

2, reflecting

What is it reflected? Speaking of this concept, the author expressed his face senseless force. I do not remember, look at a few examples below.

2.1 get the full package and class name through an object

public static void main(String[] args) {
Demo demo=new Demo();
   System.out.println(demo.getClass().getName());
}


2.2 Class class object instantiated

Class<?> demo1=null;

demo1=Class.forName("com.example.bean.Demo");

 

Note: There are many examples to baidu.com Forum Search

 

You will find in your Baidu a bit, my two simple examples also copy over. But still I want to summarize what is reflected by:


Analyzing the runtime class of any one object belongs; object constructor any class at runtime; Analyzing member variables and methods any class has at runtime; calling a specified object's method at runtime; generating dynamic proxies.

 

After reading this paragraph above explained, are not ignorant look force, it does not matter, and then to see, understand the role of reflection from the examples.


3, the micro-channel in use reflection of the public platform

/ ** 
* micro-channel event    
* /
public interface
WechatEventCenter {

/ **     * @ Function Description: micro-channel return default     * / public BaseWechatMsg DefaultEvent () ; / **     * @ Function Description: text message     * / public BaseWechatMsg text () ; / **     * @ function description: location message     * / public BaseWechatMsg lOCATION () ; / **     * @ function description: voice message     * / public BaseWechatMsg voice


   

   


   

   


   

   


   () ;
/ **     * @ Function Description: <P> event message </ P> * / public BaseWechatMsg Event () ; / **     * @ Function Description: <P> No issue when, after an event of interest for a push </ the p-> * @return * / public BaseWechatMsg the Subscribe () ; / **     * @ function description: button 1, when the corresponding button EventKey to create method names     * so here's method names look a bit strange, ah, do not press java naming specification,     * you can also define their own preferences     * / public BaseWechatMsg EVENT_HOME () ; }
   

   
   

   

   
   
   

   




   

 

/ ** 
* micro-channel access entry
** /
@RequestMapping (value = "index" )
@ResponseBody
public String WeChat (the HttpServletRequest Request , the HttpServletResponse Response ,
String Signature , String timestamp , String the nonce , String echostr) {
String Result = "" ; String Method request.getMethod = () ;    IF ( "the GET" .equals (Method)) { // access authentication return echostr ; // return directly echostr successful access will be omitted here decryption verification } the else {
   

       
   // Message Processing Result = doPost (Request) ; } return Result ; }
       
   

 

After successful access, and to focus on following up directly on the code:

private String dopost(HttpServletRequest request){

BaseWechatMsg wechatMsg;
  try {
String sReqData = WechatUtils.convertStreamToString(request.getInputStream());
     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
     DocumentBuilder db = dbf.newDocumentBuilder();
     StringReader sr = new StringReader(sReqData);
     InputSource is = new InputSource(sr);
     Document document = db.parse(is);
     Element root = document.getDocumentElement();
     Root.getElementsByTagName fromusername = String (HqWechatConstant.FromUserName) .Item ( 0 ) .getTextContent () ; the System. OUT .println ( "User:" + fromusername + "enter WeChat." ) ; The System. OUT .println ( "message to the user : \ R & lt \ n- " + sReqData) ; String msgType = root.getElementsByTagName (HqWechatConstant.MsgType) .Item ( 0 ) .getTextContent () ; wechatEventCenter.setRoot (the root) ; // parameter injection         // Get event type to be performed the method method, method wechatEventCenter.getClass = () getMethod (msgType). ;         // the method name to call reflection methods
     
     
     
     

     

     = wechatMsg (BaseWechatMsg) Method.invoke (wechatEventCenter) ; } the catch (Exception E) { // call the default method wechatMsg = (BaseWechatMsg) wechatEventCenter.defaultEvent () ; e.printStackTrace () ; } the finally { } the System. OUT .println ( "reply message is: \ R & lt \ n- ' + wechatMsg) ;   return wechatMsg.toString () ; }
 

       
       
 




Process used here on reflection, that is, the following two lines of code:

Method method = wechatEventCenter.getClass().getMethod(msgType);

wechatMsg = (BaseWechatMsg) method.invoke(wechatEventCenter);

So that the entire process is complete, in dealing with the event message is the same to call the corresponding method according to EventKey events on OK, not go into here.

 

4, summary

Analyzing the runtime class of any one object belongs; object constructor any class at runtime; Analyzing member variables and methods any class has at runtime; calling a specified object's method at runtime; generating dynamic proxies.

  

For reference only, inadequacies also please forgive me, please correct me!


End the welfare, concern " the Java union " backstage reply :

Reply [ Video ]: 100G + free learning video
reply [ books are really more ]: 1000+ books free programming ebook
reply [ plus group ]: the Java technology learning exchange group, Ali Great God and you talk technology

640?wx_fmt=png

Guess you like

Origin blog.csdn.net/zhupanlinch/article/details/102693887