I have a string representation of a class’s path. It could be any of three classes, all of which implement the same interface, Adapter, but I don’t know what the value is.
- “com.example.adapters.Music”
- “com.example.adapters.Video”
- “com.example.adapters.Photo”
Given only a variable holding one of the three strings above, how can I get a usable instance of the actual class?
You can use:
You will then have to cast
objto the correct type (possibly by examining the name or by usinginstanceof). It is easier if your classes have a common base class (or interface that they implement) and you can useobjknowing only that it is some subclass.This will only work if the class has a default constructor. Otherwise you will have to use reflection to get an instance of a constructor method and invoke it with the proper arguments.