0

Possible Duplicate:
Use string in place of variable name

Is there any way in Java that allows an object to be created using a string?

Let's say, i have a class called "Toyata", is there anyway i can create an object of Toyata using the string variable s in class Car?

public class Car{
String s = "Toyota";
}

public class Toyota{
int speed;

public Toyota(int speed){
this.speed=speed;
}

}
Community
  • 1
  • 1
Truth
  • 466
  • 1
  • 4
  • 11
  • 3
    No, you really don't want to do this with Java. Trust me. If you want to associate a String with another object, use a `Map`. This question should be closed as it has been asked and answered thousands of times before. Please Google this and you'll see. – Hovercraft Full Of Eels Oct 08 '12 at 23:19
  • Doing this is a huge sign of code smell. _Find another way._ – Louis Wasserman Oct 08 '12 at 23:36
  • From the OOP point of view, Toyota *is* a Car, therefore `public class Toyota implements Car`. If there's any generic implementation, you may want to extend `GenericCar` class: `public class Toyota extends GenericCar`, where `public class GenericCar implements Car`. Not really answer to your question, but it may be you are on the wrong track here. – maksimov Oct 08 '12 at 23:36

2 Answers2

0

You can use reflection, but you need a fully qualified classname:

https://stackoverflow.com/a/4030634/1217408

EDIT:

Hovercraft Full Of Eels's comment about using a map lookup is probably far more appropriate in this situation.

Community
  • 1
  • 1
TheZ
  • 3,663
  • 19
  • 34
  • 2
    But you shouldn't do this as there are far better ways of associating a String with a reference type object. – Hovercraft Full Of Eels Oct 08 '12 at 23:21
  • @HovercraftFullOfEels Agreed, so I added your alternative and recommended it. It's the reason _can_ is italicized, since it is what the askee wants, but hopefully the better alternative will suffice. – TheZ Oct 08 '12 at 23:22
0

You need to query for class (assuming it's in the default package this should work) via the value of s. Then you have to lookup the proper constructor via your class' getConstructor() method. Since Toyota does not contain a default constructor, you need to query for one that matches your expected parameters. In this case, it's an int. int is represented in Class form by Integer.TYPE. Finally after that is all said and done, you can call newInstance() on the constructor with the desired speed passed in and you should have a new instance ready to use. Of course there will be a few checked exceptions to handle.

Class<?> clazz = Class.forName(s);
Constructor constructor = clazz.getConstructor(new Class[] {Integer.TYPE});
Toyota toyota = (Toyota) constructor.newInstance(new Object[] {90});
Greg Giacovelli
  • 10,164
  • 2
  • 47
  • 64