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

How to check declaration value type? #284

Closed PavelTurk closed 1 year ago

PavelTurk commented 1 year ago

I need to check if declaration value type is variable. The only way I found is to check it via string, but I don't like.

This is my code:

InstanceMirror instanceMirror = reflector.reflect(object);
var classMirror = instanceMirror.type;
for (var v in classMirror.declarations.values) {
  if (v.runtimeType.toString() == "VariableMirrorImpl") { //This is what I have to do now
  }

}

I tried if (v.runtimeType is VariableMirror) but it didn't work. Could anyone say what is a proper way to do it?

eernstg commented 1 year ago

v is VariableMirror is the relevant test if you want to check whether the run-time type of the object which is bound to v is a subtype of VariableMirror.

The test v.runtimeType is VariableMirror is just another way to write false, because v.runtimeType is a reified type, that is, an object of type Type which is a representation of the run-time type of v, and an object of type Type is never of type VariableMirror (except for completely pathological examples where you want to prove that it can be done ;-).

It's similar to looking at v.getClass().getClass() in Java. You want v.getClass() instead, and in Dart that job is done by is.

In any case, this would allow you to look at all the declarations in the class mirrored by classMirror, and selecting the ones that are variable declarations (static variables or instance variables). I assume this is also what you want to do.

PS: 'value type' is a dangerous phrase to use, because there is a concept known as the 'Future value type' of an async function. For Future<int> f(int i) async { return i; } the future value type is int. So it's better to just talk about the 'type of an object', which is some DeclarationMirror in this case, and then it's unimportant that we used .values in order to get hold of it.

eernstg commented 1 year ago

I'll close this issue, it's working as intended.