Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get the class type in a static method?

Tags:

types

dart

Dart code:

class User() {
   static onmystatic() {
       printCurrentType(); // should print:  User
   }
}

Notice the printCurrentType() in the class User, is it possible to implement it? I tried this.runtimeType but it reminds me this is not in scope.

like image 385
Freewind Avatar asked Jan 17 '26 16:01

Freewind


1 Answers

Since onmystatic() is static, any functions it calls must static (or a instance method of some object), so I'll assume printCurrentType() is also static. Since static methods can't be overridden, the type is constant and you can just write:

class User {
  static onmystatic() {
    printCurrentType();
  }

  static printCurrentType() {
    print(User);
  }
}

If you wanted printCurrentType() to be some generic method that printed the type of the containing class of any static method it was called from, well... that's a much tougher task. The easiest answer is just don't try to do that and pass the class as a parameter:

class User {
  static onmystatic() {
    printCurrentType(User);
  }
}

printCurrentType(Type type) {
  print(type);
}

The complicated answer is that you could throw an exception, parse the stack trace, and try to determine by some rules which class you should print. I'll leave that as an exercise to the reader :)

like image 68
Justin Fagnani Avatar answered Jan 21 '26 09:01

Justin Fagnani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!