jeudi 19 janvier 2017

Compile time annotation processor to check that some string are valid field or method name when using reflection

I need to write some code for an UI framework (Vaadin) that uses introspection.

The idea is to bind some model field to some UI controls, like this:

FieldGroup binder = new FieldGroup(item);
binder.bind(nameField, "name");
binder.bind(ageField, "age");

Here the xField are UI controls, and "name" and "age" are Model's fields.

I've written this kind of code many dozen times over year and my experience tells me that in a near future the code won't work as expected because the field "foo" of model "bar" would be renamed...

I would like to have a set of annotations to have compile time checking about introspection/reflection.

So a String (class/instance variable or a parameter) can receive a @FieldName or a @MethodName and the annotations should be processed by a processor that can fails the build if the name is not found in the target class. The idea is to avoid runtime error and to enforce a systematic control.

The previous code would now be written:

FieldGroup binder = new FieldGroup(item);
binder.bind(nameField, @FieldName(model = MyModel.class) "name");
binder.bind(ageField,  @FieldName(model = MyModel.class) "age");

Or

   public class MyMode {
     @FieldName public static final String NAME = "name";
     @FieldName public static final String age = "age";
     ...
    }
    ...
    FieldGroup binder = new FieldGroup(item);
    binder.bind(nameField, MyModel.NAME);
    binder.bind(ageField,  MyModel.age);

I can't find any tool like this with my Google skills, so I have 2 questions:

  • is there any existing tool like this ?
  • if not, would it be interesting to have this tool ?




Aucun commentaire:

Enregistrer un commentaire