如何知道类中的字段类型

时间:2014-01-04 02:57:28

标签: dart

假设我有这样一个类:

class SomeClass {
  String name;
  int age;
}

我们如何知道nameage的类型而不指定其值,例如通过声明?

修改

type VariableMirror有{{1}}人,不知道我是怎么想的。

1 个答案:

答案 0 :(得分:1)

您可以尝试使用此代码。

import 'package:reflection/reflection.dart';

void main() {
  var variableNames = [#firstName, #age];
  testByNames(SomeClass, variableNames);
  testAllDeclaredInThisClass(SomeClass);
  testAllIncludeInherited(SomeClass);
}

void testAllIncludeInherited(Type type) {
  print("testAllIncludeInherited");
  print("----------------------");
  var ti = typeInfo(SomeClass);
  for(var vi in ti.getVariables(BindingFlags.PUBLIC | BindingFlags.PRIVATE
    | BindingFlags.INSTANCE | BindingFlags.STATIC).values) {
    var name = SymbolHelper.getName(vi.simpleName);
    var type = vi.type.reflectedType;
    print("The '$name' has type '$type'");
  }

  print("----------------------");
}

void testAllDeclaredInThisClass(Type type) {
  print("testAllDeclaredInThisClass");
  print("----------------------");
  var ti = typeInfo(SomeClass);
  for(var vi in ti.getVariables(BindingFlags.PUBLIC | BindingFlags.PRIVATE
    | BindingFlags.INSTANCE | BindingFlags.STATIC | BindingFlags.DECLARED_ONLY).values) {
    var name = SymbolHelper.getName(vi.simpleName);
    var type = vi.type.reflectedType;
    print("The '$name' has type '$type'");
  }

  print("----------------------");
}

void testByNames(Type type, List<Symbol> simpleNames) {
  print("testByNames");
  print("----------------------");
  var ti = typeInfo(SomeClass);
  for(var simpleName in simpleNames) {
    var vi = ti.getVariable(simpleName, BindingFlags.PUBLIC |
      BindingFlags.PRIVATE | BindingFlags.INSTANCE | BindingFlags.STATIC);
    if(vi != null) {
      var name = SymbolHelper.getName(simpleName);
      var type = vi.type.reflectedType;
      print("The '$name' has type '$type'");
    }
  }
  print("----------------------");
}

class BaseClass {
  String gender;
}

class SomeClass extends BaseClass {
  int age;
  String firstName;
  String lastName;
}
testByNames
----------------------
The 'firstName' has type 'String'
The 'age' has type 'int'
----------------------
testAllDeclaredInThisClass
----------------------
The 'age' has type 'int'
The 'firstName' has type 'String'
The 'lastName' has type 'String'
----------------------
testAllIncludeInherited
----------------------
The 'gender' has type 'String'
The 'age' has type 'int'
The 'firstName' has type 'String'
The 'lastName' has type 'String'
----------------------