The Artima Developer Community
Sponsored Link

Agile Buzz Forum
Accessing generic type information at runtime

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Joe Walnes

Posts: 151
Nickname: jwalnes1
Registered: Aug, 2003

Joe Walnes, "The Developers' Coach" from ThoughtWorks
Accessing generic type information at runtime Posted: Mar 7, 2005 9:36 AM
Reply to this message Reply

This post originated from an RSS feed registered with Agile Buzz by Joe Walnes.
Original Post: Accessing generic type information at runtime
Feed Title: Joe's New Jelly
Feed URL: http://joe.truemesh.com/blog/index.rdf
Feed Description: The musings of a ThoughtWorker obsessed with Agile, XP, maintainability, Java, .NET, Ruby and OpenSource. Mmm'kay?
Latest Agile Buzz Posts
Latest Agile Buzz Posts by Joe Walnes
Latest Posts From Joe's New Jelly

Advertisement

A common misconception about generics in Java 5 is that you can't access them at runtime.

What you can't find out at runtime is which generic type is associated with an instance of an object. However you can use reflection to look at which types have been staticly associated with a member of a class.

public class GenericsTest extends TestCase {

    class Thing {
        public Map<String,Integer> stuff;
    }

    public void test() throws Exception {
        Field field = Thing.class.getField("stuff");
        ParameterizedType type = (ParameterizedType) field.getGenericType();
        assertEquals(Map.class, type.getRawType());
        assertEquals(String.class, type.getActualTypeArguments()[0]);
        assertEquals(Integer.class, type.getActualTypeArguments()[1]);
    }

}

Just wanted to clear that up.

(This is something that I'll probably exploit in XStream for J5 users to further simplify the XML.)

Read: Accessing generic type information at runtime

Topic: Wiki as Application Development Platform Previous Topic   Next Topic Topic: The Posting Tool in Bottom Feeder

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use