getAnnotation<A> method

A? getAnnotation<A>()

Returns the annotation of type A, if present.

Throws a cast error if the annotation does not exist.

Example:

final scope = def.getAnnotation<Scope>();
print(scope.value); // "singleton" or "prototype"

Implementation

A? getAnnotation<A>() {
  for (final annotation in annotations) {
    if (annotation.matches<A>()) {
      try {
        return annotation.getInstance<A>();
      } catch (_) {}
    }
  }

  for (final cls in annotatedClasses) {
    try {
      final instance = cls.newInstance();
      if (instance is A) {
        return instance;
      }
    } catch (e) {
      // ignore
    }
  }
  return type.getDirectAnnotation<A>() ?? type.getAnnotation<A>();
}