Possible to resolve/parse type from string at runtime?

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

Best

Diego

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               
end                               
                                  
class Foo < Data                  
end                               
                                  
class Bar < Data                  
end                                                                
                                  
m = Hash(String,Proc(Data)).new   
                                  
m["Foo"] = ->{ Foo.new}           
m["Bar"] = ->{ Bar.new }                                           
                                  
puts m["Foo"].call                
puts m["Bar"].call                                    

Thanks…

Is the type string also within the JSON object? If you so you may be able to leverage JSON::Serializable - Crystal 1.10.1. 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.

2 Likes

+1
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:

2 Likes

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

1 Like