Java. String contents to create an object's instance
I know this is part of java.lang.reflect.* but I wasn't able to find any suggestions to point me how to tackle this.
I want to use the contents of a string to create and instance of an object 开发者_StackOverflowthat has the name of what the string stores.
Eg.
String[] carName = {"volvo","vw","bmw"};
car carName[0];
car carName[1];
car carName[2];
I've stumbled upon this snippet, which looks promising:
Car car = (Car) Class.forName("Volvo").newInstance();
It throws back: Unhandled exception type ClassNotFoundException
edit: Sorry for not being clear enough, I'm not in any way a professional. No, I don't have a class called Volvo. I'm actually trying to define one generic class (car) and then initialize instances of it via strings.
You need to either
catch
theClassNotFoundException
, or declare it to be thrown from your methodYou need to specify the fully-qualified name of your class. If the class is in packaged as
foo.cars.Volvo
, then use that as its name.
It looks as if the class you reference isn't on the classpath. Make sure you reference the full package, e.g.
com.example.Volvo
when using Class.forName()
.
Do you have a class called Volvo
which extends Car
?
Class.forName
requires a fullly qualified classname, so it might be org.example.Volvo
or whatever you've named your class.
Or are you trying to create a new car object that has a value of carName?
Edit:
Then what you're looking for is probably more like (i didn't try to compile this, so...)
string[] names = { "Volvo", "BMW", "Volkswagen" };
List<Car> cars = new ArrayList<Car>();
for(string name : cars)
{
// presuming you have a class Car with a constructor that takes a string
cars.Add(new Car(name));
}
if you already know you have a class called car, you don't need to mess with any of the reflection stuff to create one.
精彩评论