Can I get an InstanceMirror of a class without using any constructor in Dart?

266 Views Asked by At

Can I get an InstanceMirror without using any constructor in Dart?

More precisely: I have a class with or without any special constructor, yet I'd like to get an InstanceMirror without having to provide a constructor or any arguments at all.

For example PHP offers ReflectionClass::newInstanceWithoutConstructor

Cheers

2

There are 2 best solutions below

1
On

New If the class doesn't have a constructor, a default constructor with no arguments is implicitly created for this class and you can use it.

If a class has one or more explicit constructors, you can create a new instance only by using one of them.

Old
I'm not sure if I fully understand your questions, but basically - no. If your class doesn't have a constructor an implicit default constructor is used.

An instance of a class is created with new SomeClass which creates a new instance and calls the constructor. There are other ways like literals {'x': 1, 'y': 2} but I'm pretty sure this way a constructor is called as well.

1
On
  1. Why do you need an InstanceMirror and why can't you use a ClassMirror?

  2. Just list all the available constructors from the ClassMirror and then use a constructor with 0 arguments to create a new instance.

The PHP Version says: "Creates a new class instance without invoking the constructor.". For me this totally makes no sense. That's why there are constructors: To be called at creation time.