Possible to resolve/parse type from string at runtime?

I was wondering if it’s possible to create a class, from a String, at runtime.



Not like in the same way as other more dynamic languages, such as PHP. You would have to know what classes can be instantiated and use a case statement to know which one to instantiate. However this approach wouldn’t really handle aliases unless you include those also along with the FQN of the type.

Can you share a bit more about your use case? There may be a better alternative, such as using the metaclass of the class(es) instead of a string.

Hello @Blacksmoke16 ,

Sure, basically I will query json data from a database and a “type string” also. Using that type, I would like to populate the class with json data.

My first approach, which is not working…

abstract class Data               
class Foo < Data                  
class Bar < Data                  
m = Hash(String,Proc(Data)).new   
m["Foo"] = ->{ Foo.new}           
m["Bar"] = ->{ Bar.new }                                           
puts m["Foo"].call                
puts m["Bar"].call                                    


Is the type string also within the JSON object? If you so you may be able to leverage JSON::Serializable - Crystal 1.7.2. Even if it’s not, could prob make some wrapper type that has a type property from the one column, then another that has the string, and handle it that way?

Either way, I would explore that more before going down the road of using procs or case statements.


Maybe this blog by Lorenzo Barasti might help.

Just for completeness, the problem in the code is that one needs to do an upcast in the procs:


@beta @Blacksmoke16 perfect, that’s exactly what I was looking for. The blog is solving the exact issue I have.

1 Like