How to create custom class from variable? (not Object)

I know I can do do the following :

String className = "A";
Object o= Class.forName(className).newInstance();

But consider this case (simplification):

class Parent { 

   public void action() {...};
}

class A extends Parent {

 @Override
 public void action() {...};

}
class B extends Parent {

 @Override
 public void action() {...};

}
class C extends Parent {

 @Override
 public void action() {...};

}

Now I would like to create a class that can be either of those 3 cases. If I use the above code and create an Object, I wouldn't be able to call the action method. I would like to be able to create an object that extends Parent from a string.

In my actuall case I have multiple different parents, and the class is extented from a class that's extended from a class and about 4 layers of inhertiance. Would regular casting work?

Answers


Casting would work, but is unnecessary. Class#newInstance() returns an instance of type T, which is the class' generic type. This means that because Class.forName("A") returns an instance of Class<A>, you can declare your instance as Parent due to A's inheritance, as newInstance() is returning an object of type A.

Parent p = Class.forName("A").newInstance();
p.action();

Since all your classes extend Parent you can cast result of newInstance() to this type and then call all methods declared in Parent. The "right" implementation will run.

Parent p = (Parent)Class.forName(className).newInstance();
p.action();

Need Your Help

Can't get a pointer-to-structure array to work

c++ arrays data-structures

I have the following code of a pointer-to-structure array, but I can't get the Insert function working

Vim spell check automatically splits the screen

vim spell-checking

I typed z= underneath a misspelled word, and vim split the screen horizontally, thereby keeping the misspelled word in context, but also providing a list words to change the misspelled word from. U...