Advertisement
Guest User

Untitled

a guest
Aug 18th, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. public static void main(String[] args) {
  2. String json = "{ "active": false }";
  3. final MyObject myObject = new MyObject();
  4. final Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
  5.  
  6. myObject.fromGson(gson.fromJson(json, MyObject.class));
  7. for (int i = 0; i < 10; i++) {
  8. myObject.setActive(!myObject.isActive());
  9. }
  10. }
  11.  
  12. private static class MyObject {
  13. @Expose private boolean active;
  14. private static MyObject self;
  15.  
  16. public MyObject() {
  17. this.active = false;
  18. self = this; // notice where this line is located
  19. }
  20.  
  21. public static boolean active() {
  22. return self.isActive();
  23. }
  24.  
  25. public boolean isActive() {
  26. return active;
  27. }
  28.  
  29. public void setActive(boolean active) {
  30. this.active = active;
  31.  
  32. System.out.println("this: " + this.isActive());
  33. System.out.println("self: " + self.isActive());
  34. }
  35.  
  36. public void fromGson(MyObject object) {
  37. this.setActive(object.isActive());
  38. }
  39. }
  40.  
  41. this: false
  42. self: false
  43. this: true
  44. self: false
  45. this: false
  46. self: false
  47. this: true
  48. self: false
  49. this: false
  50. self: false
  51. this: true
  52. self: false
  53. this: false
  54. self: false
  55. this: true
  56. self: false
  57. this: false
  58. self: false
  59. this: true
  60. self: false
  61. this: false
  62. self: false
  63.  
  64. public MyObject() {
  65. this.active = false;
  66. }
  67.  
  68. public void fromGson(MyObject object) {
  69. self = this; // notice the new position
  70. this.setActive(object.isActive());
  71. }
  72.  
  73. this: false
  74. self: false
  75. this: true
  76. self: true
  77. this: false
  78. self: false
  79. this: true
  80. self: true
  81. this: false
  82. self: false
  83. this: true
  84. self: true
  85. this: false
  86. self: false
  87. this: true
  88. self: true
  89. this: false
  90. self: false
  91. this: true
  92. self: true
  93. this: false
  94. self: false
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement