Search code examples
dartdart-mirrors

How can I use Reflection (Mirrors) to access the method names in a Dart Class?


I need to "fetch" the methods in a Dart Class.

How can I do this?

And I want to be able to call the methods.

May I see an example?


Solution

  • Here's an easy copy-pasteable code sample:

    import 'dart:mirrors';
    import 'dart:io';
    
    main() {
      var im = reflect(new File('test')); // Retrieve the InstanceMirror of some class instance.
      im.type.methods.values.forEach((MethodMirror method) => print(method.simpleName));
    }
    

    Output is:

    existsSync
    _delete
    exists
    directory
    _getDecodedLines
    readAsTextSync
    readAsBytesSync
    readAsLinesSync
    _directory
    throwIfError
    lastModifiedSync
    readAsLines
    open
    _ensureFileService
    deleteSync
    delete
    _exists
    length
    openInputStream
    create
    _create
    readAsText
    _openStdioSync
    openOutputStream
    _fullPath
    _lastModified
    fullPathSync
    readAsBytes
    lastModified
    _openStdio
    _open
    openSync
    lengthSync
    directorySync
    fullPath
    createSync
    _lengthFromName