fork download
  1. import java.lang.annotation.ElementType;
  2. import java.lang.annotation.Retention;
  3. import java.lang.annotation.RetentionPolicy;
  4. import java.lang.annotation.Target;
  5. import java.lang.reflect.Field;
  6.  
  7. // @UserPreference marks a field that should be exported.
  8. @Retention(RetentionPolicy.RUNTIME)
  9. @Target(ElementType.FIELD)
  10. @interface UserPreference {
  11. }
  12.  
  13. // @HasUserPreferences marks a field that should be recursively scanned.
  14. @Retention(RetentionPolicy.RUNTIME)
  15. @Target(ElementType.FIELD)
  16. @interface HasUserPreferences {
  17. }
  18.  
  19.  
  20. // Your example Login class, with added annotations.
  21. class Login {
  22.  
  23. @UserPreference public String token; // <= a preference
  24. @UserPreference public String customerid; // <= a preference
  25. @HasUserPreferences public Class1 class1; // <= contains preferences
  26.  
  27. public class Class1 {
  28. @HasUserPreferences public Class2 class2; // <= contains preferences
  29. @UserPreference public String string1; // <= a preference
  30.  
  31. public class Class2 {
  32. public int int1; // <= not a preference
  33. @UserPreference public String string2; // <= a preference
  34. @UserPreference public String string3; // <= a preference
  35. }
  36. }
  37.  
  38. // Construct example:
  39. public Login () {
  40. token = "token1";
  41. customerid = "586969";
  42. class1 = new Class1();
  43. class1.string1 = "string1Value";
  44. class1.class2 = class1.new Class2();
  45. class1.class2.string2 = "string2Value";
  46. class1.class2.string3 = "string3Value";
  47. }
  48.  
  49. }
  50.  
  51.  
  52. public class Main {
  53.  
  54. // Recursively print user preferences.
  55. // Fields tagged with @UserPreference are printed.
  56. // Fields tagged with @HasUserPreferences are recursively scanned.
  57. static void printUserPreferences (Object obj) throws Exception {
  58. for (Field field : obj.getClass().getDeclaredFields()) {
  59. // Is it a @UserPreference?
  60. if (field.getAnnotation(UserPreference.class) != null) {
  61. String name = field.getName();
  62. Class<?> type = field.getType();
  63. Object value = field.get(obj);
  64. System.out.println(name + " - " + type + " - " + value);
  65. }
  66. // Is it tagged with @HasUserPreferences?
  67. if (field.getAnnotation(HasUserPreferences.class) != null) {
  68. printUserPreferences(field.get(obj)); // <= note: no casts
  69. }
  70. }
  71. }
  72.  
  73. public static void main (String[] args) throws Exception {
  74. printUserPreferences(new Login());
  75. }
  76.  
  77. }
Success #stdin #stdout 0.11s 380352KB
stdin
Standard input is empty
stdout
token - class java.lang.String - token1
customerid - class java.lang.String - 586969
string2 - class java.lang.String - string2Value
string3 - class java.lang.String - string3Value
string1 - class java.lang.String - string1Value