dart - call a method if it exists -
is there simple, lightweight/inexpensive call determine if object supports named method? so, in obj.respondsto great.
dynamic _tojson(dynamic obj) { return obj.respondsto('tojson'))? obj.tojson() : obj; } class foo { string foo = "foo.foo"; bar bar = new bar(); map tojson() { return { "foo" : _tojson(foo), "bar" : _tojson(bar) }; } }
one alternative call , catch nosuchmethod exception, imagine bad practice , expensive?
the short answer is, 'no'. answer provided frédéric hamidi not incorrect, not work in dart2js (dart:mirrors largely unimplemented in dart2js).
also, while checking whether object responds particular method common in other languages (ruby, example), not seem particularly dart-y me. maybe once mirrors supported in dart, change.
and hard whether reflection based on mirrors 'lightweight/inexpensive'. depends on use case , how define these terms.
i best bet call method on object, catch nosuchmethod exception, , implement default error-handling behavior. makes sense if expect method present.
Comments
Post a Comment