Skip to content

Instantly share code, notes, and snippets.

@mhadaily
Created August 14, 2020 07:49
Show Gist options
  • Save mhadaily/c12fbd3be3e26345cf75e7dcd6b0d96f to your computer and use it in GitHub Desktop.
Save mhadaily/c12fbd3be3e26345cf75e7dcd6b0d96f to your computer and use it in GitHub Desktop.
Get Function or Library Name in Dart Language!

reflect Returns an [InstanceMirror] reflecting reflectee. If reflecteeis a function or an instance of a class that has acallmethod, the returned instance mirror will be aClosureMirror`.Note that since one cannot obtain an object from another isolate, this function can only be used to obtain mirrors on objects of the current isolate.

A MirrorSystem is the main interface used to reflect on a set of associated libraries. At runtime each running isolate has a distinct MirrorSystem. It is also possible to have a MirrorSystem which represents a set of libraries which are not running -- perhaps at compile-time. In this case, all available reflective functionality would be supported, but runtime functionality (such as invoking a function or inspecting the contents of a variable) would fail dynamically.

simpleName getter is for Dart language entity. The simple name is in most cases the identifier name of the entity, such as 'myMethod' for a method, void myMethod() {...} or 'mylibrary' for a library 'mylibrary'; declaration.

import 'dart:mirrors';

void someFunctionToBeUsedSomeWhere(Function() cb) {
  final cm = reflect(cb) as ClosureMirror;
  final name = MirrorSystem.getName(cm.function.simpleName);
  print('--- Hey I am {$name}! ---');
}

Example:

class HeyFriend{
    void static myMethod() {}
}

someFunctionToBeUsedSomeWhere(MyFriend myMethod);
// --- Hey I am {MyMethod}! ---
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment