首页 > 解决方案 > Dart 2: How to access a class's type?

问题描述

In Swift 4, I used to do something like this to locally store objects of variable classes:

class Repo {
  var mediaType : MyBaseClass.Type

  func doSomething() {
    mediaType.someStaticMethod();
  }
}

class SpecificClass : MyBaseClass {
    static func someStaticMethod() -> void {
      // Stuff
    }
}

repo = Repo(SpecificClass.self)
repo.doSomething();  // Executes `Stuff`

Moving to Dart 2, this is the closest I've gotten, yet the error specified at the bottom is blocking me.

class Repo {
  Type mediaType;

  void doSomething() {
    mediaType.someStaticMethod();
  }
}

class SpecificClass extends MyBaseClass {
  static void someStaticMethod() {
    // Whatever
  }
}

repo = Repo(SpecificClass)
repo.doSomething()  // Should execute `Whatever`, but for the error

Which generates this error:

The method 'someStaticMethod' isn't defined for the class 'Type'

Is this sort of trick feasible with Dart 2?

标签: dart

解决方案


推荐阅读