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();

Need Your Help

How to do a MYSQL query with an array in PHP?

php mysql arrays

How can I query a database using the results of a prior query if they are in array? Below is what I have thus far.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.