google / reflectable.dart

Reflectable is a Dart library that allows programmers to eliminate certain usages of dynamic reflection by specialization of reflective code to an equivalent implementation using only static techniques. The use of dynamic reflection is constrained in order to ensure that the specialized code can be generated and will have a reasonable size.
https://pub.dev/packages/reflectable
BSD 3-Clause "New" or "Revised" License
374 stars 56 forks source link

[question] - Is it possible to have Annotations with Parameters? #298

Closed dinbtechit closed 1 year ago

dinbtechit commented 1 year ago

Is it possible to have Annotations with Parameters? This is something we could do in dart:mirrors.

Annotation Definition:

class Injectable extends Reflectable {
  final String name;
  const Injectable({this.name = ''}) : super(newInstanceCapability, declarationsCapability, invokingCapability);
}

usage

@Injectable(name: ServiceA)        // <----<< Annotation with parameters.
class ServiceA {

}

$ flutter pub run build_runner build

Error:

A reflector class must have exactly one constructor which is `const`, has 
the empty name, takes zero arguments, and uses at most one superinitializer.
Please correct `class Injectable extends Reflectable` to match this.
eernstg commented 1 year ago

No, the "reflector" class must be a direct subclass of class Reflectable from 'package:reflectable/reflectable.dart', and it must have that very specific shape which is mentioned in the error message.

However, you could simply do this:

// Reflector declaration, in 'reflector_lib.dart'.

@GlobalQuantifyMetaCapability(Injectable, Reflector())
import 'package:reflectable/reflectable.dart';

class Reflector extends Reflectable {
  const Reflector()
      : super(
            newInstanceCapability, declarationsCapability, invokingCapability);
}

class Injectable {...} // Whatever is needed.

// Usage, in some other library.
import 'reflector_lib.dart';

@Injectable(name: ServiceA)
class ServiceA {...}

I'll close the issue because I think this will address your concern. Please create a new one if needed!

dinbtechit commented 1 year ago

That worked thank you!