Results 1 to 7 of 7

Thread: Generic method

  1. #1
    jomypgeorge is offline Member
    Join Date
    May 2010
    Posts
    90
    Rep Power
    0

    Default Generic method

    is there any way to make a new instance of generic type in a generic method?
    some thing like

    Java Code:
    <T> void receive(List <T> a)
    	{
    	a.add(new <T>());
    	}
    or is it foolish to make a new instance while we don't know what is the type of that instance at run time?

  2. #2
    Petr's Avatar
    Petr is offline Senior Member
    Join Date
    Jan 2011
    Location
    Russia
    Posts
    618
    Rep Power
    4

    Default

    Hi.
    You can't create new instance from generic type, because may be situation when generic type may be have no public constructors.

  3. #3
    jomypgeorge is offline Member
    Join Date
    May 2010
    Posts
    90
    Rep Power
    0

    Default

    thanks petr,

    also we cant assure that the generic type have a constructor of the type we use

  4. #4
    Petr's Avatar
    Petr is offline Senior Member
    Join Date
    Jan 2011
    Location
    Russia
    Posts
    618
    Rep Power
    4

    Default

    However, I read about this problem. You can use (Class<E> clazz).newInstance();,
    but it makes no sense.

  5. #5
    jomypgeorge is offline Member
    Join Date
    May 2010
    Posts
    90
    Rep Power
    0

    Default

    think its using reflection ...
    right?

  6. #6
    Petr's Avatar
    Petr is offline Senior Member
    Join Date
    Jan 2011
    Location
    Russia
    Posts
    618
    Rep Power
    4

    Default

    Yes,it is. This is reflection.
    I don't understand why do you want to do this? Why do you want to use this code?

  7. #7
    jomypgeorge is offline Member
    Join Date
    May 2010
    Posts
    90
    Rep Power
    0

    Default

    i don't want to use it in actual code, but now i am learning generics in java and try to experiment with that.

    thanks petr for quick reply

Similar Threads

  1. Generic Classes
    By marciojc in forum New To Java
    Replies: 0
    Last Post: 12-17-2010, 11:34 PM
  2. Generic method problem
    By counterfox in forum New To Java
    Replies: 6
    Last Post: 10-24-2010, 06:30 PM
  3. generic code
    By mac in forum New To Java
    Replies: 4
    Last Post: 05-27-2010, 05:06 PM
  4. standard input stream storing to a generic method?
    By vendetta in forum New To Java
    Replies: 3
    Last Post: 01-29-2010, 08:13 PM
  5. generic types
    By jon80 in forum New To Java
    Replies: 6
    Last Post: 06-12-2009, 10:29 PM

Posting Permissions

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