I need to code a method, something like :
MyClassObject convert(Class MyClass , String value)
The convert method’s job is to convert the String into an object of MyClass, where MyClass can be anything (except a primitive) – Integer, Boolean, Character, Date… the possibilities are huge here – and that’s the reason I gave up my stupid if-else block to handle all the cases individually.
I could see something related to this for C# (don’t know if it works) , don’t know if we have a Java equivalent for this or this
I understand not everything can be converted from a string, I am ready to handle exceptions for non-parseable items.
I don’t know if this is possible or not. If not, please help me with a proper design pattern for my code.
Thanks !
Your best bet is probably the
ServiceLoadermechanism. This allows you to define a pair of interfaces, e.g.:… and then locate all the implementations of these interfaces available at runtime, like so:
You make your implementation of the interfaces available to
ServiceLoaderby listing them in a special file in theMETA-INFdirectory in yourjarfile; see the javadoc for details.