Warm tip: This article is reproduced from serverfault.com, please click

I can't create a new instance of a ClassMirror by calling the defaullt constructor

发布于 2020-11-30 21:22:57

I have two classes

class ESVAPI extends BibleProvider {
  ESVAPI() : super('esvapi', true, {'esv'});

 ...methods
}
abstract class BibleProvider {
  ...fields

  BibleProvider(this.name, this._requiresKey, this._versions) {
    Bible.addProvider(this, _versions.toList());
  }
}

I intend to have multiple classes extend the abstract class, so I want to create a method that creates an instances of each of BibleProvider's subclasses, I created one here:

  ClassMirror classMirror = reflectClass(BibleProvider);
  List<DeclarationMirror> subClassMirrors = currentMirrorSystem()
      .libraries
      .values
      .expand((lib) => lib.declarations.values)
      .where((lib) {
    return lib is ClassMirror &&
        lib.isSubclassOf(classMirror) &&
        lib != classMirror;
  }).toList();
  DeclarationMirror subClassDec = subClassMirrors[0];
  ClassMirror ESVCLASS = reflectClass(subClassDec.runtimeType);
  var esvObj = ESVCLASS.newInstance(const Symbol(''), []);

But on ESVCLASS.newInstance I receive this exception:

No constructor '_ClassMirror' declared in class '_ClassMirror'

I'm thinking that this may have to do with how I call the superclass in the Constructor with "hard coded" values. If this is the case, is there a way to call the subclass' constructor and have it call the super constructor? I'm not entirely sure. Anyone familiar with reflections know what may be the case?

Questioner
joshpetit
Viewed
0
lrn 2020-12-02 17:46:48

Change the last three lines to:

  ClassMirror subClassDec = subClassMirrors[0] as ClassMirror;
  var esvObj = subClassDec.newInstance(const Symbol(''), []);
  ...
  print(esvObj.reflectee.runtimeType); // ESVAPI

You are reflecting on something that is already a mirror, so your ESVCLASS becomes the class mirror of the class _ClassMirror itself, not the subclass of BibleProvider you found above. Just use the subClassDec class mirror directly.