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 !

1
  • 2
    Expando class is a good place to start as far as I understood. You can define fields, methods, whatever dynamically. Commented Apr 14, 2014 at 14:33

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.