code_junkie

In Java, how do I dynamically determine the type of an array?

Nov 11th, 2011
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.63 KB | None | 0 0
  1. Object o = new Long[0]
  2. System.out.println( o.getClass().isArray() )
  3. System.out.println( o.getClass().getName() )
  4. Class ofArray = ???
  5.  
  6. true
  7. [Ljava.lang.Long;
  8.  
  9. Class ofArray = o.getClass().getComponentType();
  10.  
  11. public <T> Class<T> testArray(T[] array) {
  12. return array.getClass().getComponentType();
  13. }
  14.  
  15. Object maybeArray = ...
  16. Class<?> clazz = maybeArray.getClass();
  17. if (clazz.isArray()) {
  18. System.out.printf("Array of type %s", clazz.getComponentType());
  19. } else {
  20. System.out.println("Not an array");
  21. }
  22.  
  23. String[] arr = {"Daniel", "Chris", "Joseph"};
  24. arr.getClass().getComponentType(); // => java.lang.String
Add Comment
Please, Sign In to add comment