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 / November 2005

Tip: Looking for answers? Try searching our database.

Creating an object during runtime

Thread view: 
Peter Jones - 29 Nov 2005 21:50 GMT
I'm trying to generate an object name during run time, and then create an
object with the contents of that variable. You can see that I'm trying to
also make the object name self generating (almost, the 'y' variable isnt
being incremented yet), putting two values ('y' and 'C'). My apologies for
poor coding structure / lack of comments, but I'm am a bit lost on how to
work it out. MANY thanks in advance.Heres what I have so far:

public class testVariable
{
       private String name = "";
       private String New_name = "";
       private int y = 2;

       public testVariable()
       {}

       public void test(String x)
       {
               name = x;
               New_name = name + y ;
               System.out.println(New_name);
       }

       public String getNew_name()
       {
               return New_name;
       }

       public static void main(String[] args)
       {
               int z = 2;
               testVariable Darren = new testVariable();
               Darren.test("C");
               testVariable "c"+ z = new testVariable();
               String Old_name = New_name;
       }      
}
Tjerk Wolterink - 29 Nov 2005 22:07 GMT
> I'm trying to generate an object name during run time, and then create an
> object with the contents of that variable. You can see that I'm trying to
> also make the object name self generating (almost, the 'y' variable isnt
> being incremented yet), putting two values ('y' and 'C'). My apologies for
> poor coding structure / lack of comments, but I'm am a bit lost on how to
> work it out.

I cannot help you if you don't document your code.
Peter Jones - 29 Nov 2005 22:43 GMT
>> I'm trying to generate an object name during run time, and then create an
>> object with the contents of that variable. You can see that I'm trying to
[quoted text clipped - 4 lines]
>
> I cannot help you if you don't document your code.
I will re-edit my code and post back as soon as I can.
zero - 29 Nov 2005 22:15 GMT
> I'm trying to generate an object name during run time, and then create
> an object with the contents of that variable. You can see that I'm
[quoted text clipped - 5 lines]
>
> public class testVariable

Please start class names with a capital letter.

> {
>         private String name = "";
>         private String New_name = "";

Please don't start variable names with a capital letter.

>         private int y = 2;
>
[quoted text clipped - 17 lines]
>                 int z = 2;
>                 testVariable Darren = new testVariable();

Please don't start variable names with a capital letter.

>                 Darren.test("C");
>                 testVariable "c"+ z = new testVariable();

This line can't possibly compile correctly.  What are you trying to do
here?

>                 String Old_name = New_name;
>         }      
> }

If you want to create objects at runtime you need the reflection api.  
For example, to create a new object of class C2:

Class classDefinition = Class.forName("C2");
Object object = classDefinition.newInstance();

Here object will be an instance of C2.

Signature

Beware the False Authority Syndrome

Peter Jones - 29 Nov 2005 23:10 GMT
> If you want to create objects at runtime you need the reflection api.
> For example, to create a new object of class C2:
[quoted text clipped - 3 lines]
>
> Here object will be an instance of C2.

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
zero - 30 Nov 2005 00:19 GMT
> 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
[quoted text clipped - 13 lines]
> 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

Signature

Beware the False Authority Syndrome

Roedy Green - 30 Nov 2005 00:55 GMT
>where the names c1, c2, ... are computed at runtime, correct?

to get that literally you have to generate class files or *.java
files on the fly and compile them.  

See http://mindprod.com/jgloss/jasm.html
http://mindprod.com/jgloss/javacexe.html
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Peter Jones - 30 Nov 2005 21:54 GMT
>> 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
[quoted text clipped - 69 lines]
>
> zero

I have ended up using a wrapper class, its almost working as desired. I'll
post back once its ready for action.
All the best.
Chris Smith - 30 Nov 2005 23:18 GMT
> 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..)

It will eventually be important for you to realize that objects simply
don't have names.  For that reason, it's impossible to answer your
question of how to create objects with certain names.  It would be like
asking a car salesman how to specify which color wings your new car will
come with.

What objects *do* have is references that point to them.  References can
be stored in variables, which *do* have names.  However, there is no way
to declare a new variable at runtime (except for, as someone pointed
out, creating a whole new class and generating Java bytecode to declare
variables in that class, then loading that class into the application at
runtime; you probably don't want to do that).

So the question is what exactly you mean by "name", and why you want to
do what you're asking for.  "Zero" took some good guesses, but this
would be easier if you'd explain yourself.  Chances are, using a HashMap
is the best option.

Signature

www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation

Stefan Schulz - 29 Nov 2005 23:36 GMT
> If you want to create objects at runtime you need the reflection api.  
> For example, to create a new object of class C2:
[quoted text clipped - 3 lines]
>
> Here object will be an instance of C2.

Just to nitpick: You create all your objects at runtime, no matter if you
use reflection, or not.

Back on topic:

As far as i can see, the original author wants to create _classes_ at
runtime, for which there are some libraries available, but nothing in the
standard API... though i doubt that this is the solution to the OPs
question. Some more details about what he is trying to do (as opposed on
how he tries to do it) might help.

Signature

You can't run away forever,
But there's nothing wrong with getting a good head start.
          --- Jim Steinman, "Rock and Roll Dreams Come Through"
         



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.