fork download
  1. import java.util.Collection;
  2. import java.util.Map;
  3. import java.lang.reflect.*;
  4.  
  5. class A {
  6. public A[] as;
  7. public Collection<String> cs;
  8. public Map<String, Integer> msi;
  9. private String s;
  10. protected int i;
  11. }
  12.  
  13. class Inspector {
  14. public static void inspect(Class<?> clazz) {
  15. try {
  16. System.out.println("Inspecting class " + clazz.getSimpleName() + ":");
  17. Field[] fields = clazz.getDeclaredFields();
  18. for (Field f : fields) {
  19. describe(f);
  20. }
  21. } catch (Exception e) {
  22. e.printStackTrace();
  23. }
  24. }
  25.  
  26. private static void describe(Field f) throws Exception {
  27. describeModifiers(f);
  28. Type t = f.getGenericType();
  29. describeType(t);
  30. System.out.println(" " + f.getName());
  31. }
  32.  
  33. private static void describeModifiers(Field f) {
  34. int modifiers = f.getModifiers();
  35. if (Modifier.isPublic(modifiers)) {
  36. System.out.print(" public ");
  37. }
  38. if (Modifier.isPrivate(modifiers)) {
  39. System.out.print(" private ");
  40. }
  41. if (Modifier.isProtected(modifiers)) {
  42. System.out.print(" protected ");
  43. }
  44. // add more if you like
  45. }
  46.  
  47. private static void describeType(Type type) {
  48. if (type instanceof ParameterizedType) {
  49. ParameterizedType pt = (ParameterizedType) type;
  50. Type[] args = pt.getActualTypeArguments();
  51. System.out.print(pt.getRawType());
  52. System.out.print("<");
  53. boolean atBegin = true;
  54. for (Type t : args) {
  55. if (atBegin) {
  56. atBegin = false;
  57. } else {
  58. System.out.print(", ");
  59. }
  60. describeType(t);
  61. }
  62. System.out.print("> ");
  63.  
  64. } else if (type instanceof GenericArrayType) {
  65. GenericArrayType arrType = (GenericArrayType) type;
  66. describeType(arrType.getGenericComponentType());
  67. System.out.println("[] ");
  68. } else if (type instanceof Class) {
  69. Class<?> clazz = (Class) type;
  70. System.out.print(clazz.getSimpleName());
  71. }
  72. // a lot of more interesing stuff can be done here
  73. }
  74. }
  75.  
  76. class Main {
  77.  
  78. public static void main(String... args) {
  79. Inspector.inspect(A.class);
  80. }
  81. }
Success #stdin #stdout 0.03s 245632KB
stdin
Standard input is empty
stdout
Inspecting class A:
 public A[] as
 public interface java.util.Collection<String>  cs
 public interface java.util.Map<String, Integer>  msi
 private String s
 protected int i