4 Replies Latest reply: Dec 1, 2008 2:16 AM by 843793 RSS

    how to determine actual type of a generic

    843793
      I'm using java 6, and I have a TypeMirror that represents the the type java.util.List<Foo>
      How do I extract the information that the list of of type Foo ?
      I've looked through the javadoc, and tried a bunch of things, but I can't figure this out.
        • 1. Re: how to determine actual type of a generic
          608410
          driver8 wrote:
          I'm using java 6, and I have a TypeMirror that represents the the type java.util.List<Foo>
          How do I extract the information that the list of of type Foo ?
          I've looked through the javadoc, and tried a bunch of things, but I can't figure this out.
          In this case the TypeMirror should be a DeclaredType (check using getKind())

          cast it to a DeclaredType which has a method getTypeArguments() which is what you are after.

          Bruce
          • 2. Re: how to determine actual type of a generic
            843793
            Thanks, that worked.

            Is there any way to get the actual type (ArrayList)
            of a field declared like the following:

            class foo {
            private List fooField = new ArrayList();
            ...
            }

            Edited by: driver8 on Nov 25, 2008 5:02 PM
            • 3. Re: how to determine actual type of a generic
              608410
              If you are using Sun's javac, then the APIs are documented at [http://java.sun.com/javase/6/docs/technotes/guides/javac/index.html]

              In particular Trees can convert from Element (which you have), across to the (non standardised) Comiler Tree API from which you can look at the initializer expression for the variable declarion. Note however that it may be more complex than just a simple instantiation and that it will not work if for example you run an annotation processor in Eclipse which uses their internal compiler.
              • 4. Re: how to determine actual type of a generic
                843793
                brucechapman wrote:
                driver8 wrote:
                I'm using java 6, and I have a TypeMirror that represents the the type java.util.List<Foo>
                How do I extract the information that the list of of type Foo ?
                I've looked through the javadoc, and tried a bunch of things, but I can't figure this out.
                In this case the TypeMirror should be a DeclaredType (check using getKind())

                cast it to a DeclaredType which has a method getTypeArguments() which is what you are after.
                A technique is more verbose but avoids the explicit cast would be to use a TypeVisitor.