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 / July 2006

Tip: Looking for answers? Try searching our database.

Instantiate a class with a variable as its name

Thread view: 
BogusException - 18 Jul 2006 02:42 GMT
The subject line says it all! This is an extension of a previous topic.

I want to create an instance of a class, but want to refer to the name
of the instance, at creation time, via a variable. So, if I were to
make 3 classes in an iterative loop, I would be able to call the
instances c1, c2, c3 programmatically.

The equivelent is close to anonymous hashes and arrays in Perl, like
$$someArrayName[0];
. OK, so its not that close!

The result is that each of the instantiated classes can then also be
addressed programmatically-without knowing their exact instance name.
So if I knew that I created 3 classes (which I would, as they were
created iteratively), I could call a method common to all 3 one at a
time.

All of the Java documentation regarding anonymity refers to inner
classes, which although powerful are not the same thing as an anonymous
name for a class instance. Is this possible in Java?

TIA!

BogusException
quazimajster - 18 Jul 2006 12:33 GMT
> I want to create an instance of a class, but want to refer to the name
> of the instance, ...

I hope you were thinking about the name of the class, not the name of
the instance.

You could do something like this:

Class myClass = Class.forName(variableWithClassName);

Object newInstance = myClass.newInstance();

I think that also Java Reflection should be helpful:

http://java.sun.com/j2se/1.5.0/docs/guide/reflection/index.html

Have a nice day.
BogusException - 18 Jul 2006 14:52 GMT
Quazi,

Thanks for the post! Unfortunately(?), I am talking about the name of
the instance. I need to create any number of instances of classes, so I
won't know the names of the instancesat runtime, nor how many there
will be.

Also, I'll need to refer to each created class programmatically. That
is, by the name given to the instance upon instantiation. The only
thing I know at runtime are the names of the classes to be
instantiated. This is where forName() is handy.

Perhaps Java can't do anonymous instantiation?

> I hope you were thinking about the name of the class, not the name of
> the instance.

Thanks in advance!

BogusException
Rogan Dawes - 18 Jul 2006 15:14 GMT
> Quazi,
>
[quoted text clipped - 16 lines]
>
> BogusException

As QuajizMaster said, you can create a new instance of an arbitrary
class at runtime using

Class myclass = Class.forName(className);

This then allows you to refer to the CLASS using the variable "myclass".

If you want to create an instance of the class, equivalent to "new
MyClass()", you can do so:

Object myInstance = myclass.newInstance();

You can repeat that newInstance() call any number of times to create a
new instance of the class. Obviously, you will want to keep a reference
to the instances, for example, in a List or a Map, so that you can
access them at a later stage.

Now, if you know that all the classes are instances of an interface, for
example "MyInterface", you can do something like:

// define the class from the variable className
Class myClass = Class.forName(className);

// create a new instance of the class, which is an implementation
// of MyInterface - cast it to MyInterface so we can execute methods
// defined in MyInterface
MyInterface myInstance = (MyInterface) myClass.newInstance();

myInstance.myMethod();

// put the instance into a List so we can create an unspecified
// number of instances
List list = new ArrayList();
list.add(myInstance);

// create a new instance, and add it to the list in one go
list.add((MyInterface) myClass.newInstance());

Now, if you don't know that the classes all implement a particular
interface, I don't know how meaningful executing arbitrary methods will
be. Nonetheless, if you are doing this, e.g. writing an IDE, etc, you
will need to investigate the Reflection API

Hope this helps.

Rogan
BogusException - 18 Jul 2006 21:44 GMT
Thanks to Rogan, Thomas and Patricia. I think it can be done, but
before I ask another clarifier I am going to try to write an example of
how I think you are suggesting it be done. Then I can post that here to
see if you think the approach I take is still valid.

To answer Thomas' and Patricia's questions in the mean time:

A series of utility classes all implement the same interface for their
methods. They are utilities because they are used in whatever order
they are needed. Some are used in some cases, some are not. All classes
are known and locally available to the super class that is tasked with
"chaining" them together for serial data processing. Imagine that the
interface defines a dataIn and dataOut method. The inclusion and order
of the utility classes is known only at runtime via a config file of
some kind.

So now you see why it is key to provision the classes in order,
programmatically, and with program derived instance names. As the
program runs, the data is passed between the utility classes, in order.
This is where Patricia's, Rogan's and Thomas' idea of using a list/map
is great. THe list/map can be traversed with the output of one module
being fed into the input of the next.

Off to code!

Thanks!

BogusException
Thomas Hawtin - 18 Jul 2006 15:19 GMT
> The subject line says it all! This is an extension of a previous topic.
>
[quoted text clipped - 16 lines]
> classes, which although powerful are not the same thing as an anonymous
> name for a class instance. Is this possible in Java?

Sounds to me like you want a List (or array)...

How does what you want differ from:

    List<C> cList = new ArrayList<C>();
    for (int ct=0; ct<num; ++ct) {
        cList.add(new C());
    }
...
    for (C c : cList) {
        c.someMethod();
    }

?

Tom Hawtin
Signature

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

Patricia Shanahan - 18 Jul 2006 20:09 GMT
> The subject line says it all! This is an extension of a previous topic.
>
[quoted text clipped - 20 lines]
>
> BogusException

I'm not quite sure what question you are asking, but if you just want to
assign dynamic names to instances of a class, use a Map, with the name
as key and the corresponding instance as value.

Patricia


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.