Re: Creating an object during runtime
- From: zero <zero@xxxxxxx>
- Date: Wed, 30 Nov 2005 00:19:09 GMT
Peter Jones <ant_on_line@xxxxxxxxxxxxxxxxxxxxxx> wrote in
news:dmin4m$d5e$1@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx:
>
> Allow me to attempt to clarify. I'm trying to make an object of type
> class, during runtime. The problem is, that I need to make the
> objectname automatically increment as the objects are created.
> e.g.
> C1 C2 C3 C4 etc.
> (list of created objects..)
> However, I cant use a variable as a parameter in the constructor, as
> it uses the variable name as the object name, not the contents of the
> variable. e.g.
> car = C1;
> vehicle car = new vehicle();
> In the above line, the new object I have created is "car" and not C1.
> I need it to be C1. Your reference to the reflection API has been
> helpful, but I dont see where I can use a variable of somekind, or
> other similar mechanism, to let me create objects with a new object
> name, incremented automatically.
> again, Many Thanks in advance
>
Ah, that's a different story. So you want something like:
SomeClass c1 = new SomeClass();
SomeClass c2 = new SomeClass();
SomeClass c3 = new SomeClass();
....
where the names c1, c2, ... are computed at runtime, correct?
Hmm... *thinking*...
I don't think this is possible. I see two possible alternatives.
Neither is exactly what you want though.
First, you could use an array.
SomeClass c[] = new SomeClass[10];
for(int i = 0; i < 10; i++)
c[i] = new SomeClass();
Here you could see your variable names as being c[0], c[1], ... instead
of c1, c2, ...
Second, you could create a wrapper class that stores one object along
with it's name.
class WrapperClass
{
String varName;
Object varData;
public WrapperClass(String name, Object data)
{
varName = name;
varData = data;
}
}
then use this as follows:
for(int i = 0; i < 10; i++)
{
WrapperClass w = new WrapperClass("c" + i, new Object());
// use w
}
here varName would be your variable name, and varData the object.
That brings me to a third alternative: just use a Map. Maps do pretty
much the same as WrapperClass, except they have more than one name-data
pair.
Hope this helps.
zero
--
Beware the False Authority Syndrome
.
- Follow-Ups:
- Re: Creating an object during runtime
- From: Roedy Green
- Re: Creating an object during runtime
- References:
- Creating an object during runtime
- From: Peter Jones
- Re: Creating an object during runtime
- From: zero
- Re: Creating an object during runtime
- From: Peter Jones
- Creating an object during runtime
- Prev by Date: Re: [ANN] AnthillPro 2.5 Build Management Server Released
- Next by Date: Re: Using PHP language in Java/JSP files.
- Previous by thread: Re: Creating an object during runtime
- Next by thread: Re: Creating an object during runtime
- Index(es):