Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get default value of a field in an abstract class

Suppose I have a class like this:

abstract class Foo {
  String name bar = 'bar';
}

Using mirror, can we get the value of bar ?

like image 623
Budi Sutrisno Avatar asked Jan 23 '14 01:01

Budi Sutrisno


People also ask

Can abstract class have default method?

An abstract class can have abstract and non-abstract methods. From Java 8, it can have default and static methods also.

Can abstract class have field?

An abstract class may have static fields and static methods. You can use these static members with a class reference (for example, AbstractClass.

Can abstract class have getters and setters?

You can do everything in an abstract class that you can do in a normal class except creating a new object only by using a constructor. This means that you can simply copy and paste the getters and setters from your subclass into your parent class.

What is the default access modifier for abstract class?

C#- Default access modifier of Abstract Class.


1 Answers

General answers:

  • You can use super.field if you're extending a class and want to access its fields/getters.
  • If you're reflecting on a class declaration, you can't currently introspect on any bodies, including method bodies, or initializers. You would have to use the analyzer or dart2js.
  • Dado is... interesting in how it works. It tries to instantiate the abstract class, and doesn't actually work anymore.

Since you were looking at Dado, let me explain more how it works, even though it's not a general answer to this question.

First, the approach with Dado was and is pretty experimental. I was trying to use the language features to require a declarative definition of modules so that authors couldn't write modules that didn't work with code-generation. There have been some changes in Dart and mirrors that make this approach less workable, or at least makes it require more boilerplate, so I'm rethinking the whole thing. Take any technique you find there with a gain or two of salt :)

For anyone else who hasn't looked at a sample or the code, in Dado you declare an abstract class for a module definition. A field with a value is declaring a fixed singleton value, similar to how a more traditional DI container might have you write bind(Foo).toValue(new Foo()).

The way I (used to) get the value is by instantiating the abstract class via mirrors, and simply then simply read the field. dart:mirrors changed to disallow instantiating abstract classes, so this no longer works. This is unfortunate, because other types of bindings were declared with abstract methods, and those cause warnings in non-abstract classes.

like image 56
Justin Fagnani Avatar answered Sep 29 '22 04:09

Justin Fagnani