Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / January 2006

Tip: Looking for answers? Try searching our database.

Class loading and Java Generic

Thread view: 
Ian - 27 Jan 2006 19:18 GMT
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.
oulan bator - 27 Jan 2006 19:35 GMT
hi,

1- yes of course, but you can get through this, using the
getConstructor() see
(http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html#getDeclaredConstruc
tor(java.lang.Class
...))

2-  I don't know, but I would like to kown
Thomas Hawtin - 27 Jan 2006 19:35 GMT
> Class cc = Class.forName("G2");
> G2 g = (G2)cc.newInstance();
[quoted text clipped - 4 lines]
> 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
Signature

Unemployed English Java programmer
http://jroller.com/page/tackline/



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2009 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.