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;
}

}
3
  • 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<String, OtherType>. This question should be closed as it has been asked and answered thousands of times before. Please Google this and you'll see. Commented Oct 8, 2012 at 23:19
  • Doing this is a huge sign of code smell. Find another way. Commented Oct 8, 2012 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. Commented Oct 8, 2012 at 23:36

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

But you shouldn't do this as there are far better ways of associating a String with a reference type object.
@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.
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});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.