Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to check if a class is abstract?

I need a way to check if a class is abstract. Could anyone help me?

like image 992
Tiago Avatar asked Oct 22 '22 17:10

Tiago


2 Answers

Unfortunately, the answer right now is: you can't.

As Justin mentioned, there is a Mirrors API for reflection capabilities. However, there doesn't seem to be a flag for "is abstract".

If this is functionality that you'd like to see, you can file a feature request here: http://dartbug.com/new

like image 69
Seth Ladd Avatar answered Oct 25 '22 18:10

Seth Ladd


You could do something like

library x;

import 'dart:mirrors';

abstract class MyAbstract {
  void doSomething();
}

class MyConcrete{
}

void main(List<String> args) {
  print('MyAbstract: ${isAbstract(MyAbstract)}');
  print('MyConcrete: ${isAbstract(MyConcrete)}');
}

bool isAbstract(Type t) {
  ClassMirror cm = reflectClass(t);
  if(cm.declarations.values.firstWhere(
      (MethodMirror mm) => mm.isAbstract == true, orElse: () => null) != null) {
    return true;
  }
  try {
    InstanceMirror i = cm.newInstance(new Symbol(''), []);
  } catch(e) {
    return (e is AbstractClassInstantiationError);
  }
  return false;
}

the newInstance part should be extended to check if there isn't a default constructor and try named constructors instead.

AFAIR there was a discussion recently if it should be allowed to instantiate an abstract class (in relation to dependency injection) if this changes above method might not work anymore but I couln't find something about it in the issue tracker.

Also star this feature request: Add a method to check if a class is abstract

like image 43
Günter Zöchbauer Avatar answered Oct 25 '22 18:10

Günter Zöchbauer