简体   繁体   中英

how to check function name in dart

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); 
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM