You need to query for class (assuming it's in the default package this should work) via the value of s
. Then you have to lookup the proper constructor via your class' getConstructor()
method. Since Toyota
does not contain a default constructor, you need to query for one that matches your expected parameters. In this case, it's an int
. int
is represented in Class
form by Integer.TYPE
. Finally after that is all said and done, you can call newInstance()
on the constructor with the desired speed passed in and you should have a new instance ready to use. Of course there will be a few checked exceptions to handle.
Class<?> clazz = Class.forName(s);
Constructor constructor = clazz.getConstructor(new Class[] {Integer.TYPE});
Toyota toyota = (Toyota) constructor.newInstance(new Object[] {90});