Search code examples
dartdart-mirrors

Getting static constant from a class using mirrors in dart


I'm trying to get the BYTES_PER_ELEMENT constant in Float32List (and other typed data arrays) using mirrors, but all I'm getting is the exception No static getter 'BYTES_PER_ELEMENT' declared in class 'Float32List'. So more generally, how can I access the static constants of a class?

import 'dart:typed_data';
import 'dart:mirrors';

main() {
  var array = new Float32List(10);

  var bytesPerElement = reflect(array).type.getField(#BYTES_PER_ELEMENT).reflectee;

  print(bytesPerElement);
}

Solution

  • new Float32List() is a factory constructor which returns a _Float32Array which doesn't have BYTES_PER_ELEMENT.

    print(reflect(array).type);
    

    prints

    ClassMirror on '_Float32Array'
    
    var bytesPerElement = 
        reflectClass(Float32List)
        .getField(#BYTES_PER_ELEMENT)
        .reflectee;
    

    prints

    4
    

    I'm pretty sure it is not possible to find a way back from _Float32Array to Float32List using mirrors.