2014-04-12 1 views
2

여기에서 다트를 사용하십시오.다트 : 변수 식별자 이름을 특정 유형의 변수에 대해서만 문자열로 변환하는 방법

위의 제목에서 알 수 있듯이 세 개의 bool 인스턴스 변수가있는 클래스가 있습니다 (아래 참조). 내가하고 싶은 일은이 인스턴스 변수의 식별자 이름을 검사하고 각각을 문자열로 출력하는 함수를 만드는 것입니다. ClassMirror 클래스 ALMOST와 함께 제공되는 .declarations getter는 이것을 수행합니다. 단, Constructor의 이름과 클래스에있는 다른 메서드의 이름도 제공한다는 점이 다릅니다. 이것은 좋지 않다. 그래서 정말로 원하는 것은 유형별로 필터링하는 방법입니다 (즉, 부울 식별자를 문자열로만 제공합니다.) 어떤 방법으로 이것을 할 수 있습니까?

class BooleanHolder { 

    bool isMarried = false; 
    bool isBoard2 = false; 
    bool isBoard3 = false; 

List<bool> boolCollection; 

    BooleanHolder() { 


    } 

    void boolsToStrings() { 

    ClassMirror cm = reflectClass(BooleanHolder); 
    Map<Symbol, DeclarationMirror> map = cm.declarations; 
    for (DeclarationMirror dm in map.values) { 


     print(MirrorSystem.getName(dm.simpleName)); 

    } 

    } 

} 

출력된다 가 isBoard2 isBoard3 boolsToStrings BooleanHolder

답변

1

샘플 코드를 isMarried.

import "dart:mirrors"; 

void main() { 
    var type = reflectType(Foo); 
    var found = filter(type, [reflectType(bool), reflectType(int)]); 
    for(var element in found) { 
    var name = MirrorSystem.getName(element.simpleName); 
    print(name); 
    } 
} 

List<VariableMirror> filter(TypeMirror owner, List<TypeMirror> types) { 
    var result = new List<VariableMirror>(); 
    if (owner is ClassMirror) { 
    for (var declaration in owner.declarations.values) { 
     if (declaration is VariableMirror) { 
     var declaredType = declaration.type; 
     for (var type in types) { 
      if (declaredType.isSubtypeOf(type)) { 
      result.add(declaration); 
      } 
     } 
     } 
    } 
    } 

    return result; 
} 

class Foo { 
    bool bool1 = true; 
    bool bool2; 
    int int1; 
    int int2; 
    String string1; 
    String string2; 
} 

출력 :

bool1 
bool2 
int1 
int2