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] - how to get Constructor arguments? #299

Closed dinbtechit closed 1 year ago

dinbtechit commented 1 year ago

Hi, How to get the list of constructor arguments? to dynamically create the instance..

Annotations:

class Component extends Reflectable {...}
class Injectable extends Reflectable {...}
// Usage

@Injectable()
class ServiceA {}

@Injectable()
class ServiceB { }

@Component()
class MyWidget {
  MyWidget(ServiceA serviceA, ServiceB serviceB);  // <---<< How to access these two parameters
}

Somewhere the code, Logic for the Annotation

var componentClassMirror = const Component().annotatedClasses.first;

// Q. How to get the list of constructor arguments? 
// To pass them in the below method to create an instance of the class
var instanceOfComponent = componentClassMirror.newInstance('',  [ ???])
eernstg commented 1 year ago

Here's an example showing how to use the source code exploration part of the mirror system to find information about function declarations, including constructor declarations, and their parameters: https://github.com/google/reflectable.dart/blob/master/test_reflectable/test/declarations_test.dart.

This would allow you to take the componentClassMirror.declarations and search for constructors, look up their parameters, and inspect the type of any given parameter.

dinbtechit commented 1 year ago

That worked! thank you so much for quick response!