2

I want to create a symbol equal to that of a private MethodMirror's simplename. However, Symbol's documentation states the argument of new Symbol must be a valid public identifier. If I try and create a const Symbol('_privateIdentifier') dart editor informs me that evaluation of this constant expression will throw an exception - though the program runs fine, and I am able to use it without any issues.

void main(){
  //error flagged in dart editor, though runs fine.
  const s = const Symbol('_s');
  print(s); //Symbol("_s");
}

It seems the mirror system uses symbols.

import 'dart:mirrors';
class ClassA{
  _privateMethod(){}
}

void main(){
  var classMirror = reflect(new ClassA()).type;
  classMirror.declarations.keys.forEach(print);
  //Symbol("_privateMethod"), Symbol("ClassA")
}

Is the documentation/error flagging in dart editor a legacy bug due to an outdated dart analyzer? Or are there plans to enforce this public requirement in future? Is there another way to create a unique identifying symbol that will be minified to the same symbol as the declaration's simple name

4

2 回答 2

3

如果它没有抛出,那么 VM 在 const Symbol 构造函数中有一个错误。

问题是“_s”不能识别私有变量,也不能说明它属于哪个库。符号构造函数有第二个参数,LibraryMirror因为这个原因,传入一个私有名称而不传入一个镜像应该抛出。如果不回避 const 构造函数的要求(不执行代码!),在 const 构造函数中很难做到这一点,这可能是 VM 不处理它的原因。它需要在编译器级别进行特殊处理。

你也会发现const Symbol('_s')不一样#_s。后者为当前库创建一个私有符号,前者(如果它运行)创建一个名为“_s”的非私有符号,这并不是真正有用的。例如print(identical(#_s, const Symbol('_s')));打印错误。

于 2015-03-18T06:11:30.393 回答
1

要获取符号,我认为您需要从对象中获取它。例如

  reflect(thing).type.declarations.keys.firstWhere(
    (x) => MirrorSystem.getName(x) == "_privateThingIWant");
于 2015-03-19T16:16:20.263 回答