Simple Application of Java reflection mechanism and java reflection mechanism
I have always felt that the reflection mechanism of java is very powerful, but there are not many available ones. When I was learning about android, I always wanted to implement the function of hanging up the phone, but the system did not provide open api interfaces. I checked that reflection mechanisms are used on the Internet to implement this function, which is really powerful, very practical.
In the corresponding web development today, the client needs to submit parameters to the server and write the corresponding bean file, but each time it needs to splice its internal key-value, it was quite troublesome. I suddenly remembered the reflection mechanism and tried it. It was really easy to use. Let's take a look at the code below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
Public class Bean { String name; String property; Public String getName (){ Return name; } Public void setName (String name ){ This. name = name; } Public String getProperty (){ Return property; } Public void setProperty (String property ){ This. property = property; } } |
The above is a Bean class with two attributes. When requesting the server, I need to splice it into name = xxx & property = xxx. It's okay, many of these factors need to be abstracted. The reflection mechanism is used to splice them.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
Import java. io. UnsupportedEncodingException; Import java. lang. reflect. Field; Import java.net. URLEncoder; Import java. util. HashMap; Import java. util. Map;
Public class ParamsUtil { Public static void main (String [] args) throws IllegalArgumentException, IllegalAccessException, UnsupportedEncodingException { // Set attributes Bean bean = new Bean (); Bean. setName ("blog.androiddevelop.cn "); Bean. setProperty ("master ");
// Obtain all variables Field [] fields = bean. getClass (). getDeclaredFields ();
StringBuffer sb = new StringBuffer (""); For (int I = 0; I <fields. length; I ++ ){ Sb. append (fields [I]. getName ()); Sb. append ("= "); Sb. append (URLEncoder. encode (String. valueOf (fields [I]. get (bean )), "UTF-8 ")); If (I <fields. length-1) Sb. append ("&"); } System. out. println (sb. toString ()); } } |
In this way, the parameters are spliced. Of course, this also has some drawbacks. the variables in the objects to be processed cannot be very complex types.
For more articles, goXiaopengxuan.