mmaceachran
mmaceachran

Reputation: 3348

Using Class.forName() and instantiating the class

I have a database which has a list of class names that I want to put in a a List<MyInterface>.

I do this:

List<MyInterface> list = new ArrayList<MyInterface>();
for(...) {
    MyInterface obj = (MyInterface)Class.forName(myClassString).newInstance();
    list.add(obj);
}

This works fine.

Is there any way to cast the new instance into myClassString and not the interface?

Something like:

"myClassString" concreteObject = (myClassString)Class.forName(myClassString).newInstance();

Upvotes: 0

Views: 291

Answers (2)

Bohemian
Bohemian

Reputation: 425033

If you know the actual class, don't use Class.forName(), just use new:

MyClass obj = new MyClass();

Upvotes: 0

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236004

Sure, as long as you know the concrete class:

List<MyClass> list = new ArrayList<MyClass>();
for (...) {
    MyClass obj = (MyClass) Class.forName(myClassString).newInstance();
    list.add(obj);
}

...But it's a better object oriented practice to use interfaces instead of concrete classes, so I'd leave the code as it is - with no changes.

Upvotes: 1

Related Questions