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 / First Aid / January 2007

Tip: Looking for answers? Try searching our database.

How do I get an instance of a class given its name?

Thread view: 
Knute Johnson - 31 Dec 2006 18:57 GMT
If I know the name of a class, is it possible to get an instance using
just the name?

Thanks,

Signature

Knute Johnson
email s/nospam/knute/

Flo 'Irian' Schaetz - 31 Dec 2006 19:09 GMT
And thus spoke Knute Johnson...

> If I know the name of a class, is it possible to get an instance using
> just the name?

Example: Your class is called "Test" in the package "test":

Test t = (Test)Class.forName("test.Test").newInstance();

...of course, you'll need some try/catch for this.

Flo
Knute Johnson - 31 Dec 2006 19:39 GMT
> And thus spoke Knute Johnson...
>
[quoted text clipped - 8 lines]
>
> Flo

So how then do I pass a parameter to the constructor?

Thanks,

Signature

Knute Johnson
email s/nospam/knute/

Flo 'Irian' Schaetz - 31 Dec 2006 19:49 GMT
And thus spoke Knute Johnson...

> So how then do I pass a parameter to the constructor?

Class[] c = { Integer.class, String.class };
Object[] o = { new Integer(4), "Hello" };
Test t = (Test)Class.
 forName("test.Test").
 getConstructor(c).
 newInstance(o);

For...

public Test(Integer i, String s) {...}

Flo
Knute Johnson - 31 Dec 2006 20:03 GMT
> And thus spoke Knute Johnson...
>
[quoted text clipped - 12 lines]
>
> Flo

Thanks Flo, that worked like a charm!

Signature

Knute Johnson
email s/nospam/knute/

Fred Kleinschmidt - 03 Jan 2007 18:03 GMT
>> And thus spoke Knute Johnson...
>>
[quoted text clipped - 14 lines]
>
> Thanks Flo, that worked like a charm!

This seems to be a bit silly. In the code above, you say:
  Test t = (Test)Class.forName(...).....

Why not just
  Test t = new Test(...);

That is, since you declare 't' to be of type Test, you already
must have information about that class from some import.

However,  if 't' is known to be of type Mytype or some
possibly unknown subclass of MyType, then it might
make sense to use:
  Class c = Class.forName( name );
  MyType t = (MyType)c.newInstance();
      or
  MyType t = (MyType )c.getConstructor(...).newInstance(...);

where MyType is known from some import.
But I would hope that you would check 'c' to ensure it is
indeed a MyType before you try creating an instance of it.
Signature

Fred L. Kleinschmidt
Boeing Associate Technical Fellow
Technical Architect, Software Reuse Project

Flo 'Irian' Schaetz - 03 Jan 2007 18:27 GMT
And thus spoke Fred Kleinschmidt...

> This seems to be a bit silly. In the code above, you say:

Nope. That was me. Not him.

>    Test t = (Test)Class.forName(...).....
>
> Why not just
>    Test t = new Test(...);

Because sometimes you just have the name of the class as a String.

> That is, since you declare 't' to be of type Test, you already
> must have information about that class from some import.

Of course, it's just a simplified example, nothing more. :-)

Flo
Fred Kleinschmidt - 04 Jan 2007 16:07 GMT
> And thus spoke Fred Kleinschmidt...
>
[quoted text clipped - 8 lines]
>
> Because sometimes you just have the name of the class as a String.

But then you do not know beforehand that the string is "Test",
so how can you know that it is legal to cast it to a Test?
And if you do klnow beforehand that it is guaranteed to be
a Test, why not just use
   test t = new Test();
and dispense with parsing a name that you already know will
be "Test".

My comment was to show that you can create a Test instance
only if you know that the argument to forName() is the name of
the Test class or one of its subclasses.
Thus you use
  Class c = Class.forName()
and check the results to see if it really is a Test. Otherwise
your code may throw an illegal cast exception.

>> That is, since you declare 't' to be of type Test, you already
>> must have information about that class from some import.
>
> Of course, it's just a simplified example, nothing more. :-)

Signature

Fred L. Kleinschmidt
Boeing Associate Technical Fellow
Technical Architect, Software Reuse Project

Flo 'Irian' Schaetz - 04 Jan 2007 21:37 GMT
And thus spoke Fred Kleinschmidt...

> But then you do not know beforehand that the string is "Test",
> so how can you know that it is legal to cast it to a Test?
[quoted text clipped - 3 lines]
> and dispense with parsing a name that you already know will
> be "Test".

Normaly you will not randomly create instances of classes :-) So it's
more likely, that you get the name of a class as a string, for example,
that is supposed to implement, for example, a specific interface.

> My comment was to show that you can create a Test instance
> only if you know that the argument to forName() is the name of
> the Test class or one of its subclasses.

Of course you have to test many details. But again: It's just a
simplified example, I didn't write the exception and I didn't think it
was needed to specify all tests. I am rather sure, that Knute didn't
want to do it like Test t = ... :-)

Flo


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



©2008 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.