Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Java > Class loading and Java Generic

Reply
Thread Tools

Class loading and Java Generic

 
 
Ian
Guest
Posts: n/a
 
      01-27-2006
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.

 
Reply With Quote
 
 
 
 
oulan bator
Guest
Posts: n/a
 
      01-27-2006
hi,

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

2- I don't know, but I would like to kown

 
Reply With Quote
 
 
 
 
Thomas Hawtin
Guest
Posts: n/a
 
      01-27-2006
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/
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
not just generic type programming,but also parallism generic syntaxprogramming?? minlearn C++ 2 03-13-2009 05:17 PM
generic interfaces with generic methods Murat Tasan Java 1 02-03-2009 12:17 PM
Generic class in a non generic class nramnath@gmail.com Java 2 07-04-2006 07:24 AM
Nested Class, Member Class, Inner Class, Local Class, Anonymous Class E11 Java 1 10-12-2005 03:34 PM
Generic class literals - e.g,, Class<Map<String, Integer>>.class Purush Java 4 04-13-2005 08:40 PM



Advertisments