Page 1 of 2 12 LastLast
Results 1 to 20 of 22
  1. #1
    Muskar is offline Member
    Join Date
    Nov 2010
    Posts
    73
    Rep Power
    0

    Default Getting the class of a type parameter

    I'm posting this in here since I'm only almost a year inside the programmer's world, so I still have some big gaps in my Java knowledge and because I'm actually unsure when something is "Advanced Java".

    Basically the question is the title: How can I get the class of a type parameter?

    My intention is eventually to get all the getters of a class of the type T:
    Java Code:
    Method[] methods = [B][COLOR="red"]T.class[/COLOR][/B].getMethods();
    for(Method method : methods){
        if(method.getName().startsWith("get") &&
            (method.getParameterTypes().length == 0 &&
                void.class.equals(method.getReturnType()))) {
            //Do stuff
        }
    }
    Although T.class is not allowed.

    Which solutions are there? My goal is to find the best solution but any suggestion is accepted - to help me get there.

    The only thing I found was an example where they create a new instance of T so you can call getClass() on that object:
    Java Generics: Instantiating Objects Of Type Parameter Without Passing Class Literal To Instance

    Although I'd like to know if anyone have alternative solutions.

    Thanks so much in advance!
    Last edited by Muskar; 06-02-2011 at 02:39 AM. Reason: Edited for clarification

  2. #2
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,759
    Rep Power
    7

    Default

    Let me see if I understand, you have found a solution to your problem but you say "screw that I want a different solution".

  3. #3
    Muskar is offline Member
    Join Date
    Nov 2010
    Posts
    73
    Rep Power
    0

    Default

    Quote Originally Posted by Junky View Post
    Let me see if I understand, you have found a solution to your problem but you say "screw that I want a different solution".
    I assume that you think that the messy code I linked to is a proper solution - and judging solely from your post count I trust your opinion and will just try to build my solution around that, and see if I will run into troubles when I come into the testing phase.

    Thing is, I'm really trying to create a general JTable-subclass that takes objects (like a JList takes an Object[]) instead of an Object[][] of variables - and I'd therefore prefer it to be as optimized as possible - but I'll look elsewhere if you don't want to help.

  4. #4
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,759
    Rep Power
    7

    Default

    No I wasn't referring to the "messy code". I was referring to your statement about what you found by doing some research.

  5. #5
    Muskar is offline Member
    Join Date
    Nov 2010
    Posts
    73
    Rep Power
    0

    Default

    Quote Originally Posted by Junky View Post
    No I wasn't referring to the "messy code". I was referring to your statement about what you found by doing some research.
    I don't understand.. are you criticizing the way I formulated what I need help with - or what is this about?

  6. #6
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,759
    Rep Power
    7

    Default

    I don't understand either.
    The only thing I found was an example where they create a new instance of T so you can call getClass() on that object:
    Java Generics: Instantiating Objects Of Type Parameter Without Passing Class Literal To Instance
    Does this solve your problem or not?

  7. #7
    Muskar is offline Member
    Join Date
    Nov 2010
    Posts
    73
    Rep Power
    0

    Default

    Quote Originally Posted by Junky View Post
    I don't understand either.
    As I was trying to say, I'm trying to find the best solution, not just any solution. But perhaps this is not the forum for this kind of request?

    I'm asking because I'm under the impression that it's not an optimal solution - although I'm not experienced enough with code-behind to know for sure.

  8. #8
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,759
    Rep Power
    7

    Default

    As long as your code works and doesn't take 6 hours to run then who cares if your solution is optimal or not. As you gain more experience as a Java programmer you might learn of better solutions. But for now why waste time trying to improve your code when it probably doesn't need it?
    Last edited by Junky; 06-02-2011 at 02:47 AM. Reason: Stoopid forum software. Why does it repeat the last word on the next line?

  9. #9
    Muskar is offline Member
    Join Date
    Nov 2010
    Posts
    73
    Rep Power
    0

    Default

    Alright, I ran the first test and discovered that the code doesn't work. It throws a NullPointerException (at the greenline) because the following if-sentence (marked red) isn't true:
    Java Code:
    T t = null;
    ArrayList<String> resultList = new ArrayList<String>();
    Type type = getClass().getGenericSuperclass();d
    [B][COLOR="red"]if (type instanceof ParameterizedType)[/COLOR][/B] {
        ParameterizedType paramType = (ParameterizedType)type;
        System.out.println(paramType.getClass().getName());
        Class<T> tClass = (Class<T>) paramType.getActualTypeArguments()[0];
        try {
            t =  tClass.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
    Method[] methods = [COLOR="lime"]t.getClass()[/COLOR].getMethods();
    for(Method method : methods){
        if(method.getName().startsWith("get") &&
                (method.getParameterTypes().length == 0 &&
                        !void.class.equals(method.getReturnType()))) {
            resultList.add(method.getName().substring(3));
        }
    }
    Object[] tmp = resultList.toArray();
    columnNames = new String[tmp.length];
    for (int i = 0; i < tmp.length; i++) {
        columnNames[i] = (String)tmp[i];
    }
    I created a simple 'Person' class with a String name and an int age (and getters and setters to both) to test this.

    - I don't have a clue why it doesn't work.
    Last edited by Muskar; 06-03-2011 at 12:23 PM.

  10. #10
    Muskar is offline Member
    Join Date
    Nov 2010
    Posts
    73
    Rep Power
    0

    Default

    I apologize for double-posting but I'm off the first page, so it's either bumping or creating a new topic.

    I can add that this is most likely a Java Reflection question.

    EDIT: Maybe I'd like this to be moved to Advanced Java and see if I make progress over there.
    Last edited by Muskar; 06-03-2011 at 12:34 PM.

  11. #11
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,184
    Rep Power
    19

    Default

    Quote Originally Posted by Muskar View Post
    Maybe I'd like this to be moved to Advanced Java and see if I make progress over there.
    Done.

    db

  12. #12
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,184
    Rep Power
    19

    Default

    Quote Originally Posted by Muskar View Post
    Alright, I ran the first test and discovered that the code doesn't work. It throws a NullPointerException (at the greenline) because the following if-sentence (marked red) isn't true:

    <snip code>

    I created a simple 'Person' class with a String name and an int age (and getters and setters to both) to test this.

    - I don't have a clue why it doesn't work.
    Have you read the API for ParameterizedType? What in that API leads you to believe that
    a simple 'Person' class with a String name and an int age (and getters and setters to both)
    would be an instanceof ParameterizedType?

    db

  13. #13
    Muskar is offline Member
    Join Date
    Nov 2010
    Posts
    73
    Rep Power
    0

    Default

    Quote Originally Posted by DarrylBurke View Post
    Have you read the API for ParameterizedType? What in that API leads you to believe that

    would be an instanceof ParameterizedType?

    db
    Thanks for the reply.
    I never used ParameterizedType before and I didn't read the API until now - but I'm still not sure I understand what it is - or has to do with my goal.
    All the code, that is an attempt to get the class of T, is taken from the mentioned link above.
    I only had an idea of what it could be doing but now that it doesn't work I have no clue what it has to do with getting the class of T.
    Basically all I understood, of what I read in the API, was that Type is implemented in Class, and that ParametizedType is extended from Type.

    My goal is to be able to put any class, like the Person-class, as replacement of T and then retrieve the class from it so I can get it's getters etc.
    Maybe I should mention that my current impression of T is that it represents a 'wildcard'-class - a class that isn't defined yet but will be later on. At least that's how I've used it over the past few months (just in case I'm wrong about that).
    Last edited by Muskar; 06-03-2011 at 04:05 PM.

  14. #14
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,306
    Rep Power
    25

    Default

    I don't think you can get the type of a class used this way in generics.
    Do a search on the forum. I think There were attempts at this in the last year.

    I think its documented in the Java Tutorial.

  15. #15
    Muskar is offline Member
    Join Date
    Nov 2010
    Posts
    73
    Rep Power
    0

    Default

    Quote Originally Posted by Norm View Post
    I don't think you can get the type of a class used this way in generics.
    Do a search on the forum. I think There were attempts at this in the last year.

    I think its documented in the Java Tutorial.
    I did a handful of new searches but I couldn't find anything related to my problem.
    Do you recall some words from some of those posts that I could search for?
    Because I think I'm too narrow-minded to figure any more alternative keywords to search for right now.

  16. #16
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,306
    Rep Power
    25

    Default

    Read the Tutorial Generics section. Especially near the last page.

  17. #17
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,184
    Rep Power
    19

    Default

    My goal is to be able to put any class, like the Person-class, ... so I can get it's getters etc.
    java.beans.Introspector

    db

  18. #18
    dlorde is offline Senior Member
    Join Date
    Jun 2008
    Posts
    339
    Rep Power
    7

    Default

    Quote Originally Posted by Norm View Post
    I don't think you can get the type of a class used this way in generics.
    I'm not sure exactly what the issue is, but you can certainly get the class of a parameterized type:
    Java Code:
    class Foo {
        public <T> void printArgClassName(T arg) {
            System.out.println(arg.getClass().getSimpleName());
        }
    
        public static void main(String[] args) {
            String bar = "bar";
            Float barf = 12.34f;
            Foo foo = new Foo();
            foo.printArgClassName(bar);
            foo.printArgClassName(barf);
        }
    }
    Outputs:

    String
    Float

  19. #19
    Muskar is offline Member
    Join Date
    Nov 2010
    Posts
    73
    Rep Power
    0

    Default

    Quote Originally Posted by dlorde View Post
    I'm not sure exactly what the issue is, but you can certainly get the class of a parameterized type:
    Java Code:
    class Foo {
        public <T> void printArgClassName(T arg) {
            System.out.println(arg.getClass().getSimpleName());
        }
    
        public static void main(String[] args) {
            String bar = "bar";
            Float barf = 12.34f;
            Foo foo = new Foo();
            foo.printArgClassName(bar);
            foo.printArgClassName(barf);
        }
    }
    Outputs:

    String
    Float
    My problem is that I don't have an object of T in my class and I'm not planning on getting one. I have an ArrayList<T> though - but I'm not aware of any way to get it's parametrized type - and the list is allowed to be empty, so I can't just get an object inside it.

    Otherwise that's exactly what I need.

    @Norm, call me blind but I can't seem to find anything on this subject in the entire Generics Tutorial (if it this you're talking about: http://download.oracle.com/javase/tu...xtra/generics/).

    @DarrylBurke, it seems like it's meant for GUI components and not classes, or am I wrong?
    Last edited by Muskar; 06-03-2011 at 09:16 PM.

  20. #20
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,306
    Rep Power
    25

    Default

    I searched my archive and found this comment by JosAH in August 2010
    JosAH:
    I understand your problem; unfortunately there is no way during runtime to find the type Double in, say,
    List<Double> due to type erasure; if the list is empty (i.e. not containing at least one Double) you're
    out of luck. Would it be possible to keep an 'exemplar'? (a SmallTalk thingie). The type of the exemplar
    would be the type of the elements in your collection. Even a String representation of the type will do.
    Do a search here on erasure. There are lots of hits.

Page 1 of 2 12 LastLast

Similar Threads

  1. Class as a Parameter.
    By Soxman04 in forum New To Java
    Replies: 2
    Last Post: 05-12-2011, 06:36 PM
  2. Class<T> in method parameter
    By Onra in forum New To Java
    Replies: 4
    Last Post: 03-14-2011, 12:12 AM
  3. doubt regarding <type parameter>
    By subith86 in forum New To Java
    Replies: 7
    Last Post: 03-01-2011, 03:35 PM
  4. Passing final parameter from a class
    By ianyappy in forum New To Java
    Replies: 8
    Last Post: 12-02-2010, 07:06 PM
  5. passing an enum type as a parameter ??!
    By SCS17 in forum New To Java
    Replies: 11
    Last Post: 07-13-2008, 01:44 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •