Tiago
Tiago

Reputation: 143

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?

Upvotes: 5

Views: 300

Answers (3)

Ardent Coder
Ardent Coder

Reputation: 3995

It is possible via reflection.

In furtherance of the discussion that had occurred here on the missing functionality, the required "isAbstract" feature was committed after about a year on Jan 9, 2014 (as visible from the history at GitHub).

The dart:mirrors library makes it achievable quite easily:

Dart SDK

  • dart:mirrors
    • ClassMirror
      • isAbstract

Demo

import 'dart:mirrors';

class ConcreteClass {}

abstract class AbstractClass {}

void main() {
  ClassMirror mirroredClass;

  mirroredClass = reflectClass(ConcreteClass);
  print(mirroredClass.isAbstract); // false

  mirroredClass = reflectClass(AbstractClass);
  print(mirroredClass.isAbstract); // true
}

Documentation: https://api.dart.dev/dev/2.0.0-dev.40.0/dart-mirrors/ClassMirror/isAbstract.html

Upvotes: 0

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657731

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

Upvotes: 1

Seth Ladd
Seth Ladd

Reputation: 120689

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

Upvotes: 2

Related Questions