开发者

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.


  1. You need to either catch the ClassNotFoundException, or declare it to be thrown from your method

  2. You 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜