Passing a String to the name of an object

Tag: string , object Author: fengyxj Date: 2014-02-03

If I have a variable,

String teamName;

And I am creating an object, ie.

Thread teamName = new Thread(new cheerLoop());

Can I create a Thread name based on what is contained in the teamName variable? I am trying to run a loop that will create threads based upon the inputted name. Thanks for any help!

Best Answer

The second argument of the Thread constructor can be a name, so

Thread t = new Thread(new cheerLoop(), teamName);


Note that a thread's name is a property of the thread object and not the same thing as the name of a variable. If you are interested in making a variable with a name known only at run time then you can use a more dynamic language, or, if you are using Java, store the objects in a hash map indexed by names, or use the property.

(Aside: It's a little unusual to create threads directly these days; we tend to use pools and executor services and such things, just FYI. This S.O. question might have information for you on how to do this with thread pools.)

Other Answer1

Sorry, I don't think this is the possible in any OOP language. You might wanna look this topic on Stack Overflow: Creating a variable name using a String value