swap () implementations in Java1. Today the lovely TAM teacher sent a topic, using the Java write method to Exchange integer type data, and the entry is fixed, the topic please:
If the entry is fixed, then the thought is to redefine an integer type of itself, let it have get and set method, until see the Great God, the code is as follows:
Public Static void throws Exception { = Integer. class. Getdeclaredfield ("value"); Field.setaccessible (true); ^ b); ^ b); ^ b); }
at that time, the reflection can be so used, but also can modify the final modified value,Write it down!then tan teacher released his answer, only two lines, to achieve the demand, I also startled for the human nature
public static void Swap (Integer A,integer b) throws Exception { System.out.println ("After a =" + B + "after B =" + a); System.exit (0); }
Sure enough, knowledge and wisdom are indispensable! haha!2. Finally comes out a question, set () and Setint () exactly where the difference is, brothers can be explored, because the set method after the result is not what we want
public static void Swap3 (Integer A,integer b) throws Exception { Field field = Integer.class.getDeclaredField (" Value "); Field.setaccessible (true); Integer tmp = A; Field.set (A, b); Field.set (b, TMP); }
Finally, you are welcome to leave a message, welcome the great God answer!
Swap () implementations in Java