Class loading and Java Generic

I

Ian

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.
 
T

Thomas Hawtin

Ian said:
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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top