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. // The @UserPreference annotation:
  8. @Retention(RetentionPolicy.RUNTIME)
  9. @Target(ElementType.FIELD)
  10. @interface UserPreference {
  11. }
  12.  
  13. // Example class has 4 fields, 3 are tagged with @UserPreference:
  14. class Example {
  15. @UserPreference String description;
  16. @UserPreference int quantity;
  17. @UserPreference double weight;
  18. String secret;
  19. Example () {
  20. description = "Tribble";
  21. quantity = 10000;
  22. weight = 0.48;
  23. secret = "Note: Trouble";
  24. }
  25. }
  26.  
  27. public class Main {
  28.  
  29. static void printPreferences (Object o) {
  30. for (Field f : o.getClass().getDeclaredFields()) {
  31. if (f.getAnnotation(UserPreference.class) != null) {
  32. try {
  33. String name = f.getName();
  34. Object val = f.get(o);
  35. System.out.println(name + "=" + val);
  36. } catch (IllegalAccessException x) {
  37. System.err.println("Skipping inaccessible field: " + x);
  38. }
  39. }
  40. }
  41. }
  42.  
  43. public static void main(String[] args) {
  44. printPreferences(new Example());
  45. }
  46.  
  47. }
  48.  
Success #stdin #stdout 0.1s 380352KB
stdin
Standard input is empty
stdout
description=Tribble
quantity=10000
weight=0.48