I’m currently developing a REST app. Have a NXCommand class and it subclasses that handles different commands on the server side got from a JSON command received. Each JSON request has a “command” attribute that the server needs to be created.
I am trying to instantiate these subclasses via introspection, but I can’t find a way to pass a string and instantiate an object. Will appreciate anything to avoid the select case.
P.S: Each NXCommand handles instance references until the process is done and finally deallocates the object.
Rough outline but you should get the idea: You could use GetTypeInfo in App.Open to populate a dictionary with the key of the class name and value of the TypeInfo. Then you lookup the TypeInfo from the dictionary, use GetContructors on the returned TypeInfo, and finally invoke the Constructor with the two parameters (Me, JData). Since everything descends from the same class, you can call the necessary methods on the object created to do whatever is necessary.
I don’t think so. You would do something like this in App.Open:
//classesDict is a dictionary property added to the app
classesDict = new xojo.core.dictionary
classesDict.value("NXCommand") = GetTypeInfo(NXCommand)
classesDict.value("NSWelcome") = GetTypeInfo(NXWelcome)
//continued for all of your classes
Then when you receive your JSON command you can do something like:
dim info as introspection.TypeInfo = App.classesDict.lookup(Command,nil) //Command is the same variable you did select case on
if info = nil then Break //shouldn't happen unless the JSON is messed up
Dim constructors() As Introspection.ConstructorInfo = info.GetConstructors
dim newInstance as NXCommand = constructors(0).Invoke(Me,JData)
//do something with the instance
Hopefully that makes more sense?
This came up in another thread a while ago and basically it said that adding such a feature would mean dead code stripping couldn’t occur since all classes would have to be included in the executable for such a feature to work. So although I like the idea, I definitely prefer to do this manually so that unused classes can be stripped out by the compiler.
I personally prefer the select case approach as it’s much clearer what is going on. You still have to enumerate each class explicitly with introspection, but that code is far away from where you actually use them. I think it’s better to have everything all in one spot. Easier to understand and maintain.