How to instantiate class from String?

I would not suggest to use reflection for that. You have a limited number of classes you want to instantiate, so what you usually do in software engineering is using a factory pattern.

Just create a factory that takes in a string and creates your class. The advantage over reflection is speed and also it is less error prone.

Or try to think about, if the car characteristic “mo, sd, dave” could not be an attribute of the class? Why does it have to be it’s own class (does it even have it’s own behaviour)? The need to use reflection usually is an indicator of a problem in your object oriented architecture and not the solution to it.

4 Likes