Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflect non-imported class

I'm trying to get the properties of a dynamic Class name (also trying to instantiate it) but the next code doesn't work because I think I need to import the dart file that has the Class code in the file where I want to reflect it:

//I import the file in other Dart file
import 'MyClass.dart'; //This only have a class named MyClass with some properties
import 'OtherClass.dart'

class mainClass {
  void mainFunction () {
    var properties = OtherClass.getProperties('MyClass');
  }
}

Here is the OtherClass contents:

import "dart:mirrors";

class OtherClass {
  static getProperties (String className) {
    ClassMirror cm = reflectClass(className);
    for (var m in cm.declarations.values)
      print(MirrorSystem.getName(m.simpleName));
  }
}

is there anyway to reflect a class that is not imported in the actual Dart file?

Hope this makes sense, thanks in advance.

like image 482
Ultranuke Avatar asked Oct 30 '25 05:10

Ultranuke


1 Answers

You need to find the library containing the class first. Use currentMirrorSystem().libraries to get all libraries imported in your application. If you want to avoid disambiguities, add unique library declarations to your library and pass the library name to getProperties() for exact lookups.

import "dart:mirrors";

class OtherClass {
  static getProperties(String className) {
    var classSymbol = new Symbol(className);
    var libs = currentMirrorSystem().libraries;
    var foundLibs = libs.keys.where((lm) =>
        libs[lm].declarations.containsKey(classSymbol) &&
            libs[lm].declarations[classSymbol] is ClassMirror);
    if (foundLibs.length != 1) {
      throw 'None or more than one library containing "${className}" class found';
    }
    ClassMirror cm = libs[foundLibs.first].declarations[classSymbol];
    for (var m
        in cm.declarations.values) print(MirrorSystem.getName(m.simpleName));
  }
}
like image 192
Günter Zöchbauer Avatar answered Nov 01 '25 12:11

Günter Zöchbauer