Class loading and Java Generic

Discussion in 'Java' started by Ian, Jan 27, 2006.

  1. Ian

    Ian Guest

    I am new to java class loading. In using it, I have two questions based
    on the following code:

    Class cc = Class.forName("G2");
    G2 g = (G2)cc.newInstance();

    1. When calling newInstance() to initialize "g", should G2 have to have
    a default constructor without any parameters (i.e. public G2() {...}) ?
    If yes, is there anyway to get around this if every G2's constructor
    has at least one parameter? If no, how to call newInstance() in a
    proper way?

    2. What if G2 is a Java Generic class, e.g., G2<String, Int>? I tried
    it. Except some "parameterize" warning messages at compile time, it
    works fine. But my question is, is it safe?

    Thanks.
    Ian, Jan 27, 2006
    #1
    1. Advertising

  2. Ian

    oulan bator Guest

    oulan bator, Jan 27, 2006
    #2
    1. Advertising

  3. Ian wrote:
    >
    > Class cc = Class.forName("G2");
    > G2 g = (G2)cc.newInstance();
    >
    > 1. When calling newInstance() to initialize "g", should G2 have to have
    > a default constructor without any parameters (i.e. public G2() {...}) ?
    > If yes, is there anyway to get around this if every G2's constructor
    > has at least one parameter? If no, how to call newInstance() in a
    > proper way?


    Get a Constructor from the Class and call newInstance on that.
    Class.newInstance should be avoided anyway because of its eccentric
    exception behaviour.

    > 2. What if G2 is a Java Generic class, e.g., G2<String, Int>? I tried
    > it. Except some "parameterize" warning messages at compile time, it
    > works fine. But my question is, is it safe?


    It's a good idea to avoid using generic types in this sort of situation.
    Kind of difficult with serialisation, but such is life.

    Tom Hawtin
    --
    Unemployed English Java programmer
    http://jroller.com/page/tackline/
    Thomas Hawtin, Jan 27, 2006
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Purush
    Replies:
    4
    Views:
    1,606
    Purush Rudrakshala
    Apr 13, 2005
  2. Murat Tasan
    Replies:
    1
    Views:
    8,025
    Chaitanya
    Feb 3, 2009
  3. Replies:
    2
    Views:
    423
  4. David Segall
    Replies:
    2
    Views:
    427
    Thomas Kellerer
    Jan 2, 2007
  5. minlearn
    Replies:
    2
    Views:
    445
    red floyd
    Mar 13, 2009
Loading...

Share This Page