0

I'm trying to use Java annotations to be able to add specific fields to an object.

The need is the following : I have a class that processes configuration files where keys are associated with values with the form key=value.

The problem is that I want to be able to let the user defining himself required fields which, if not present, throws exception.

The easiest solution is to pass these fields to the constructor in a String[] but, I also want the user to be able to use these required fields as it were properties of the class, so he's able to write in the code something like :

@RequiredFields(
    field1,
    field2,
    field3)
MyClass myObject = new MyClass(String filePath);
String value = myObject.field1;

and the field field1 is also a completion proposal ?

I'm actually developping in Groovy, so if not possible in standard Java, would it be in Groovy ?

Thanks !

Augier
  • 352
  • 4
  • 14
  • 2
    `Expando` class is a good place to start as far as I understood. You can define fields, methods, whatever dynamically. – Opal Apr 14 '14 at 14:33

1 Answers1

0

What about a factory method which does the validation? Something like:

MyClass my = MyClassFactory.create("arg1", "arg2")

Or, with maps on Groovy:

def my = MyClassFactory.create arg1: "foo", arg2: "bar"

And the factory itself checks the properties file.


If you really want the annotation, maybe the Type Annotations on JDK 8 are an option.

On Groovy, you can try a local AST, which seems like an overengineered solution to me, or GContracts which is programming by contract.

You could combine a factory with GContracts to @Ensure the resulting object contains all fields according to the properties file.

Will
  • 14,348
  • 1
  • 42
  • 44
  • If he is developing in Groovy, then he doesn't really need to use annotations at all, right? Unless he uses that annotation to provide a set of properties that can be used and any property not in the list would be considered an error. – mikemil Apr 15 '14 at 04:16
  • This is the point. The aim is to add properties to the object (in particular, and not to the class, which is pretty easy) that would be filled by reading the property file at the instanciation, and that could be used in the IDE right after, like they were explicitly declared in the class, with auto-completion assistance. – Augier Apr 15 '14 at 08:24