I need a way to check if a class is abstract. Could anyone help me?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With