Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to accept multiple types in Java annotation parameter?

I would like to use an annotation on a key string to configure the initial value for a property of that key. E.g.,

@NodeProperty(initialValue = "bar") static final String "FOO";

Other code later processes the annotation, adding a key "FOO" with value "bar" to a particular key-value store, if key "FOO" doesn't already exist.

My annotation declaration is:

@Retention(RetentionPolicy.RUNTIME)
@interface NodeProperty {
    long initialValue();  // I want to accept Strings, ints, byte[], etc. here.
}

But, I don't know the type of initialValue ahead of time. I'd like to accept all primitives, Strings, and arrays of the these.

Any ideas on how to accomplish this?

Edit:

Unfortunately, it sounds like overloading the annotation parameter isn't currently possible. The answers below contain various workarounds.

like image 651
David B. Avatar asked Apr 18 '26 00:04

David B.


1 Answers

Accept a single type (likely String) and use type conversion to get it from what-you-got to what-the-field-is. Similar to how Commons BeanUtils or XWork allow registering type converters to get from string form values to arbitrary Java classes.

like image 65
Dave Newton Avatar answered Apr 19 '26 12:04

Dave Newton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!