iT邦幫忙

0

Dart Symbol 的問題

  • 分享至 

  • xImage

第一次發問
有不足的地方請見諒

最近在學習Dart
在TW511教學網上自主學習
看到Symbol的範例時(出處:http://tw511.com/24/250/9174.html)
出現ClassMirror的錯誤
上網爬文找不到相關排除說明
只好上來求救
程式碼及錯誤如下

main() { 
   Symbol lib = new Symbol("foo_lib"); 
   Symbol clsToSearch = new Symbol("Foo");  
   reflect_InstanceMethods(lib, clsToSearch); 
}  
void reflect_InstanceMethods(Symbol libraryName, Symbol className) { 
   MirrorSystem mirrorSystem = currentMirrorSystem(); 
   LibraryMirror libMirror = mirrorSystem.findLibrary(libraryName); 
   if (libMirror != null) { 
      print("Found Library"); 
      print("checkng...class details.."); 
      print("No of classes found is : ${libMirror.declarations.length}"); 
      libMirror.declarations.forEach((s, d) => print(s));  
      if (libMirror.declarations.containsKey(className)) print("found class");
      ClassMirror classMirror = libMirror.declarations[className]; 
      print("No of instance methods found is ${classMirror.instanceMembers.length}");
      classMirror.instanceMembers.forEach((s, v) => print(s)); 
   } 
}    

https://ithelp.ithome.com.tw/upload/images/20220416/20148310l3fJV3mV7N.png

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
galaxian85
iT邦新手 4 級 ‧ 2022-04-18 10:32:25
main() { 
   Symbol lib = new Symbol("foo_lib"); 
   Symbol clsToSearch = new Symbol("Foo");  
   reflect_InstanceMethods(lib, clsToSearch); 
}  
void reflect_InstanceMethods(Symbol libraryName, Symbol className) { 
   MirrorSystem mirrorSystem = currentMirrorSystem(); 
   LibraryMirror libMirror = mirrorSystem.findLibrary(libraryName); 
   if (libMirror != null) { 
      print("Found Library"); 
      print("checkng...class details.."); 
      print("No of classes found is : ${libMirror.declarations.length}"); 
      libMirror.declarations.forEach((s, d) => print(s));  
      if (libMirror.declarations.containsKey(className)) print("found class");
      ClassMirror classMirror = libMirror.declarations[className]; 
      print("No of instance methods found is ${classMirror.instanceMembers.length}");
      classMirror.instanceMembers.forEach((s, v) => print(s)); 
   } 
}    

LibraryMirror.declarations 是一個 Map
你用 key 去存取 value 的話結果可能會是 null or LibraryMirror
而新版的 dart 已經強制限制變數不能 assign null
所以那一行會出錯

不過你前面已經用 if (libMirror.declarations.containsKey(className)) 檢查過確實有這個 key 了
所以下面直接改寫成
ClassMirror classMirror = libMirror.!declarations[className];
就可以了

小杰 iT邦新手 5 級 ‧ 2022-04-19 22:21:51 檢舉

還是不行
不過謝謝你的回覆
https://ithelp.ithome.com.tw/upload/images/20220419/20148310nkUF7ycn00.png

不好意思, 打反了
應該是 ClassMirror classMirror = libMirror!.declarations[className];

小杰 iT邦新手 5 級 ‧ 2022-04-20 21:09:12 檢舉

還是不行
https://ithelp.ithome.com.tw/upload/images/20220420/20148310leRxi2Erqg.png

我要發表回答

立即登入回答