美文网首页
Dart语言基础之反射

Dart语言基础之反射

作者: 星空下奔跑 | 来源:发表于2019-04-14 10:59 被阅读0次
    import 'dart:mirrors';
    import 'dart_metadata.dart';
    
    @Todo("me", "class")
    class MirrorTest {
      static num staticvar;
      static num _staticvar;
    
      num instancevar;
      static const num constvar = 1;
      final num fialvar;
    
      @Todo("me", "var")
      num metadatavar;
    
      MirrorTest({this.fialvar, this.instancevar});
    
      static void staticMethod() {
        print("staticMethod");
      }
    
      void instanceMethod() {
        print("instanceMethod");
      }
    
      @Todo("me", "method")
      void metadataMethod() {}
    }
    
    void main(List<String> args) {
      var classMirror = reflectClass(MirrorTest);
    
      /// Named Contructor
      var instanceMirror = classMirror.newInstance(
          Symbol.empty, [], {Symbol("fialvar"): 0, Symbol("instancevar"): 2});
      MirrorTest instance = instanceMirror.reflectee;
      print(instance.runtimeType);
    
      /// Class level metadata
      classMirror.metadata.forEach((metadata) {
        print(metadata.reflectee.who + "==>" + metadata.reflectee.what);
      });
    
      ///invoke static method
      classMirror.invoke(Symbol("staticMethod"), []);
    
      ///invoke instanceMirror method
      instanceMirror.invoke(Symbol("instanceMethod"), []);
    
      ///print all fields name, metadatas
      classMirror.declarations.forEach((Symbol key, DeclarationMirror value) {
        if (value is VariableMirror) {
          print("|" + value.simpleName.toString());
          print("--" + value.runtimeType.toString());
          print("--" + value.type.toString());
          print("--" + value.type.reflectedType.toString());
          value.metadata.forEach((metadata) {
            print("---" + metadata.reflectee.who + "==>" + metadata.reflectee.what);
          });
        }
      });
    
      ///print all mehtods,metadatas
      classMirror.declarations.forEach((Symbol key, DeclarationMirror value) {
        if (value is MethodMirror) {
          print(value.simpleName);
          value.metadata.forEach((metadata) {
            print("---" + metadata.reflectee.who + "==>" + metadata.reflectee.what);
          });
    
          value.parameters.forEach((param) {
            param.metadata.forEach((metadata) {
              print(
                  "---" + metadata.reflectee.who + "==>" + metadata.reflectee.what);
            });
          });
        }
      });
    }
    
    

    相关文章

      网友评论

          本文标题:Dart语言基础之反射

          本文链接:https://www.haomeiwen.com/subject/bnejwqtx.html