how to check function name in dart

637 Views Asked by At

I found this answer, but this is not working because this is road syntax. I want to check if there is a function with the same name as the hash attribute in python.

import 'dart:mirrors';

class Test {
  method1() => "hello";
}

main() {
  print(existsFunction("main")); // true
  print(existsFunction("main1")); // false
  print(existsMethodOnObject(new Test(), "method1")); // true
  print(existsMethodOnObject(new Test(), "method2")); // false
}

bool existsFunction(String functionName) => currentMirrorSystem().isolate
    .rootLibrary.functions.containsKey(functionName);

bool existsMethodOnObject(Object o, String method) => reflect(o).type.methods
    .containsKey(method); 
1

There are 1 best solutions below

0
mezoni On BEST ANSWER
import 'dart:mirrors';

class Test {
  method1() => "hello";
}

main() {
  print(existsFunction("main")); // true
  print(existsFunction("main1")); // false
  print(existsMethodOnObject(Test(), "method1")); // true
  print(existsMethodOnObject(Test(), "method2")); // false
  print(existsMethodOnType<Test>("method1")); // true
  print(existsMethodOnType<Test>("method2")); // false
}

bool existsFunction(String functionName) => currentMirrorSystem()
    .isolate
    .rootLibrary
    .declarations
    .values
    .any((e) => e is MethodMirror && e.simpleName == Symbol(functionName));

bool existsMethodOnObject(Object o, String method) => reflect(o)
    .type
    .declarations
    .values
    .any((e) => e is MethodMirror && e.simpleName == Symbol(method));

bool existsMethodOnType<T>(String method) => reflectClass(T)
    .declarations
    .values
    .any((e) => e is MethodMirror && e.simpleName == Symbol(method));

Output:

true
false
true
false
true
false