2 Replies Latest reply: Mar 11, 2010 2:10 PM by 843798 RSS

    Getting generic type from Collection

    843798
      If I have a class like this:
      public class Myclass
      {
           private Collection<String> collection;
           
           public Myclass()
           {
                collection = new ArrayList<String>();
           }
      
           public Collection<String> getCollection()
           {
                return collection;
           }
      
           public void setCollection(Collection<String> collection)
           {
                this.collection = collection;
           }
      }
      How can I use reflection to determine the generics parameter to the Collection object? (In this case, I want to get the String class)
        • 1. Re: Getting generic type from Collection
          DrClap
          For the Class object there's getGenericInterfaces and getGenericSuperclass. For the Field object there's getGenericType. Perhaps other reflection-related classes have methods whose names start with "getGeneric" too.
          • 2. Re: Getting generic type from Collection
            843798
            I had to finesse it a little, but I got it to work with this:
            MyClass sandbox = new MyClass();
            Class<?> c = sandbox.getClass();
            Class<?> t = (Class<?>) ((ParameterizedType) c.getDeclaredFields()[0].getGenericType()).getActualTypeArguments()[0];
            I realize it's not a generic solution, but the point was to see if I could get what I needed. Now I get to make this generic.

            Thanks for your help