Is there a way to access default values in an annotation statically? - java

Suppose you have some annotation Annot:
#Retention(/*your retention policy*/)
#Target(/*targeted element type*/)
public #interface Annot {
String value() default "Hello World!";
}
And in some related code, say, an annotation processor, you need the default value of the value() Annotation field without having access to a class that is annotated with #Annot. Of course you could simply do
public static final String ANNOT_VALUE_DEFAULT = "Hello World!";
in your processor class, then change the following in #Annot:
String value() default Processor.ANNOT_VALUE_DEFAULT;
(Processor being the class name of your annotation processor). While this works fine with Strings, the change in #Annot fails when your value() type is an enum. It might fail for other values, too, but enum is part of my use case, therefore if this doesn't work, it doesn't matter if other types will work.
Now, of course, the simplest way to resolve this is to simply have the default value specified in #Annot and Processor, separately. But every programmer knows that duplicated constants are not a good idea in general. You might want to automatically reflect changes in one part (e.g. #Annot) in the other parts (e.g. Processor). For this to work, you'd have to be able to do this:
var defaultVal = Annot.value(); // statically (without an instance annotated with #Annot) access default value
So, is this static access in any way possible?
Partial solution
It is not urgent for me to find a solution right now as I already found a semi-convenient workaround (see my answer). Still, because the workaround is a bit "hacky", I want to know if there is a more elegant way to do this.

Workaround
If it turns out that there is no satisfying solution to this, but you, the reader, really need a solution, take a look at this workaround:
So, the problem is that you want to access the default value without being supplied with a class that is annotated with #Annot. Well, who says that you don't have access to such a class? Just add this (preferably package-private) class to your source code:
#Annot
class DefaultAnnotValues {
private static final Annot ANNOT = DefaultAnnotValue.class.getAnnotation(Annot.class);
static SomeEnum value = ANNOT.value();
// add all other enum fields with default values here
private DefaultAnnotValues() {
}
}
Now you can access all default values of your annotation, and when you change a default value in the annotation definition, it will be automatically reflected to wherever you use those defaults.

Related

parametrize #Interface annotation in Java

I have an #interface annotation type like this -
public #interface someAnnotation {
String someVar() default "var_value";
}
I want to parametrize someVar on a Junit5 test similar to this
#ParametrizedTest
#ValueSource(strings = {"val1","val2"})
#someAnnotation(someVar = ??)
void theTestMethod(String s){
//test something
}
I want the value of s (that is provided by valueSource) to be loaded to someVar. Obviously something like this won't work -
#someAnnotation(someVar = s)
I have also tried using Test Extension by implementing BeforeEachCallback to get ExtensionContext using which someVar can be accessed but I have found no way to get ValueSource values or method parameters values from ExtensionContext. Is there any way to achieve this?
The Java Language Specification section on annotations says, in brief, that element values must not be null and may only be:
constant expressions
class literals
enum constants
arrays whose elements are one of the above
Therefore, what you're asking for isn't permitted by the language.
The only way I know of to achieve this kind of variability over an annotation's values in a test would be to have the test generate source code and compile it on the fly (or, equivalently, generate bytecode directly).
Stylistically, I would argue that unless your #ValueSource has more than ~50 elements, it's simpler and clearer to the reader to just write out each case like:
#Test
#someAnnotation(someVar = "val1")
void theTestMethodVal1(){
theTestMethodHelper("val1");
}
#Test
#someAnnotation(someVar = "val2")
void theTestMethodVal2(){
theTestMethodHelper("val2");
}
void theTestMethodHelper(String s){
//test something
}
All that having been said, it's not clear to me what the goal of tests like this might be.
As is clear from the hard-coding of "val1" and "val2" in the bodies of the above methods, it's much clearer and more concise to simply inline a needed value in the body of a method, rather than jumping through the reflection hoops that would be necessary to read that same value dynamically from an annotation on the method.

Force Uniform Constructor and Method Annotation Values?

I'm writing a custom API using Reflection to save Objects to file. I have the following class structure:
#Constructor
public XYZPOJO(#Key(key = "word") String word, #Key(key = "variations") ArrayList<String> varList) {
this.word = word;
this.varList = varList;
}
String word;
ArrayList<String> varList = new ArrayList<String>();
#Key(key = "word")
public String getWord() {
return word;
}
#Key(key = "variations")
public ArrayList<String> getVarList() {
return varList;
}
When saving Object to file, my program retrieves each method annotated with #Key, invokes method and saves invoked value to file using the value of #Key as the property name. Later, when I want to construct instance of Object it will search for constructor annotated with #Constructor and then retrieve value of #Key of each parameter in constructor and retrieve value of key (property) from file.
My main issue is that for every field I want to persist I need to duplicate the #Key annotation (and value) before each method and before the corresponding parameter in constructor. Moreover, if both the constructor/method annotation do not match exactly it will fail to instantiate Object. It is very easy to accidentally copy the wrong values.
Is there a way to define each #Key just once?
I was thinking of adding #Key just once before each field I wish to persist however I believe (please correct me if I'm wrong) that I would no longer be able to instantiate class via constructor (I believe I would need to instantiate class by directly setting value of each field via reflection, thereby circumventing constructor, correct?). However, this is not ideal since the constructor performs certain necessary functions before the class is instantiated.
What other solution(s) are there?
Thanks!
You could do that like every other library for serialization (or just switch to one of these libraries, as they all support everything you do), so possible solutions:
Skip annotation by default and just use name of getter (like getMoney -> money) and use annotation only in constructor. And on getter if you want to use other name in serialized form. Additionally you can look for field with same name to check annotations on it too, but it's optional and not needed.
Annotate only parameters in constructor but allow to set both name and property name (by default you can assume that name == property unless someone provided both values) And later you can change it to getter method name, like that money -> getMoney (just add get and make first letter upper case)
Apply 1st idea but also use parameter names from constructor that are available in runtime if someone compiles code with -parameters flag. And then you don't need any annotation, unless you want to use different name in serialized form, then just add annotation to only field/getter.
Note:
Typical libraries just scan for public methods to find properties. So they look for methods that starts with get or is followed by upper case letter, that have no arguments and some return type. As typical data class will look like that.

How to set a default value of a variable to another one in the same annotation

I'm searching for a way to set the default value of a variable in an annotation to another variable in the same annotation, here is what I want to do:
public #interface Command {
String commandName();
String triggerName() default commandName();
String description() default "";
}
By doing this, I'm getting an error with Eclipse, which is :
The value for annotation attribute Command.triggerName must be a constant expression
So I'm not entirely sure to understand it, maybe it's asking me to change "commandName" to a constant variable (with final), but I only can put public and abstract.
Is there a way to do what I'm explaining ?
You can't do that, because as indicated defaults must be compile-time constants. The closest you can do is what Spring 4.3 does, implement the logic in your reader code (such as an annotation processor or runtime reflection) and document it.

ElementType.LOCAL_VARIABLE annotation type

I`d like to create my own annotations to annotate some local variable. To write the annotation is not the problem, the problem is to get the information of them at the Runtime. I could only get some information from annotated methods or method parameters, but not from local variables. Is there any way to get it?
My own annotation is something like that:
public void m(int a)
#MyOwnAnnotation(some information)
int b = 5;
}
Or, as an alternative, is there any way to get the code of the method, to parse it further and finally get annotation value?
Thanks in advance.
With reflection you can't retrieve a local variable. So you can't retrieve an annotation on a local variable via reflection. I think that this kind of annotation is only used for compiler warnings.
You can look http://www.eclipse.org/aspectj/doc/released/adk15notebook/annotations.html
Local variable annotations are not retained in class files (or at runtime) regardless of the retention policy set on the annotation type. See JLS 9.6.1.2.
If you wan't to retrieve method code, you can use JavaParser (http://javaparser.org/).
As of Java 8, local variable annotations are retained in class files. As noted by Erick Hagstrom, this long-standing bug was fixed by JSR 308, which also added type annotations to the Java language.
However, Java's reflection API has not been updated to give access within method bodies. You will need to parse the classfile yourself. You can use a tool such as ASM. EDIT: I don't recommend JavaParser, because it has not been updated beyond Java 1.5. JavaParser has been updated.
JLS 9.6.1.2 does indeed state that local variable annotations are not retained. However, JSR 308 is working its way through the community process. It should give you the capability you need.
If you want an interim solution, here is an implementation of JSR 308.
At the moment, as mentioned in some other posts, you cannot retrieve a local variable value simply from the annotation alone.
However, I did have a simimlar issue and managed to come up with a solution using fields. Sample code is below:
Interface Class
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.FIELD)
public #interface test{
}
PoJo
public class testObject{
#test
private String one;
private String two;
//Getters and Setters
}
Get Object values
public void getFields (Object obj){
Field fields = obj.getClass().getDeclaredFields();
for (Field f : fields){
test fieldAnnotation = f.getAnnotation(test.Class);
if (fieldAnnotation != null){
f.get(obj);
// Do things here based on the values
}
}
}
Main Class
public static void main(String[] args){
//Create object
testObject test = new testObject();
test.setOne("testOne");
test.setTwo("testTwo");
getFields(test);
}
Hopefully this helps in explaining how you can get the fields for an object based on the annotation. You are simply using the annotation to 'mark' the fields you want to retrieve and then reading the value from the object.

Compiletime validation of enum parameters

There is a constructor with three parameters of type enum:
public SomeClass(EnumType1 enum1,EnumType2 enum2, EnumType3 enum3)
{...}
The three parameters of type enum are not allowd to be combined with all possible values:
Example:
EnumType1.VALUE_ONE, EnumType2.VALUE_SIX, EnumType3.VALUE_TWENTY is a valid combination.
But the following combination is not valid:
EnumType1.VALUE_TWO, EnumType2.VALUE_SIX, EnumType3.VALUE_FIFTEEN
Each of the EnumTypes knows with which values it is allowed to be combined:
EnumType1 and the two others implement a isAllowedWith() method to check that as follows:
public enum EnumType1 {
VALUE_ONE,VALUE_TWO,...;
public boolean isAllowedWith(final EnumType2 type) {
switch (this) {
case VALUE_ONE:
return type.equals(Type.VALUE_THREE);
case VALUE_TWO:
return true;
case VALUE_THREE:
return type.equals(Type.VALUE_EIGHT);
...
}
}
I need to run that check at compile time because it is of extreme importance in my project that the combinations are ALWAYS correct at runtime.
I wonder if there is a possibility to run that check with user defined annotations?
Every idea is appreciated :)
The posts above don't bring a solution for compile-time check, here's mine:
Why not use concept of nested Enum.
You would have EnumType1 containing its own values + a nested EnumType2 and this one a nested EnumType3.
You could organize the whole with your useful combination.
You could end up with 3 classes (EnumType1,2 and 3) and each one of each concerned value containing the others with the allowed associated values.
And your call would look like that (with assuming you want EnumType1.VALUE_ONE associated with EnumType2.VALUE_FIFTEEN) :
EnumType1.VALUE_ONE.VALUE_FIFTEEN //second value corresponding to EnumType2
Thus, you could have also: EnumType3.VALUE_SIX.VALUE_ONE (where SIX is known by type3 and ONE by type1).
Your call would be change to something like:
public SomeClass(EnumType1 enumType)
=> sample:
SomeClass(EnumType1.VALUE_ONE.VALUE_SIX.VALUE_TWENTY) //being a valid combination as said
To better clarify it, check at this post: Using nested enum types in Java
So the simplest way to do this is to 1) Define the documentation to explain valid combinations and
2) add the checks in the constructor
If a constructor throws an Exception than that is the responsibility of the invoker. Basically you would do something like this:
public MyClass(enum foo, enum bar, enum baz)
{
if(!validateCombination(foo,bar,baz))
{
throw new IllegalStateException("Contract violated");
}
}
private boolean validateCombination(enum foo, enum bar, enum baz)
{
//validation logic
}
Now this part is absolutely critical. Mark the class a final, it is possible that a partially constructed object can be recovered and abused to break your application. With a class marked as final a malicious program cannot extend the partially constructed object and wreak havoc.
One alternative idea is to write some automated tests to catch this, and hook them into your build process as a compulsory step before packaging/deploying your app.
If you think about what you're trying to catch here, it's code which is legal but wrong. While you could catch that during the compilation phase, this is exactly what tests are meant for.
This would fit your requirement of not being able to build any code with an illegal combination, because the build would still fail. And arguably it would be easier for other developers to understand than writing your own annotation processor...
The only way I know is to work with annotations.
Here is what I do I mean.
Now your constructor accepts 3 parameters:
public SomeClass(EnumType1 enum1,EnumType2 enum2, EnumType3 enum3){}
so you are calling it as following:
SomeClass obj = new SomeClass(EnumTupe1.VALUE1, EnumTupe2.VALUE2, EnumTupe1.VALUE3)
Change the constructor to be private. Create public constructor that accept 1 parameter of any type you want. It may be just a fake parameter.
public SomeClass(Placeholder p)
Now you have to require to call this constructor while each argument is annotated with special annotation. Let's call it TypeAnnotation:
SomeClass obj = new SomeClass(TypeAnnotation(
type1=EnumType1.VALUE1,
type2=EnumTupe2.VALUE2,
type3=EnumTupe1.VALUE3)
p3);
The call is more verbose but this is what we have to pay for compile time validation.
Now, how to define the annotation?
#Documented
#Retention({RetentionPolicy.RUNTIME, RetentionPolicy.SOURCE})
#Target(PARAMETER)
#interface TypeAnnotation {
EnumType1 type1();
EnumType2 type3();
EnumType3 type3();
}
Please pay attention that target is PARAMETER and retention values are RUNTIME and SOURCE.
RUNTIME allows reading this annotation at runtime, while SOURCE allows creating annotation processor that can validate the parameters at runtime.
Now the public constructor will call the 3-parameters private construcor:
public SomeClass(Placeholder p) {
this(readAnnotation(EnumType1.class), readAnnotation(EnumType2.class), readAnnotation(EnumType3.class), )
}
I am not implementing readAnnotation() here: it should be static method that takes stack trace, goes 3 elements back (to caller of the public costructor) and parses annotation TypeAnnotation.
Now is the most interesting part. You have to implement annotation processor.
Take a look here for instructions and here for an example of annotation processor.
You will have to add usage of this annotation processor to your build script and (optionally) to your IDE. In this case you will get real compilation error when your compatibility rules are violated.
I believe that this solution looks too complicated but if you really need this you can do this. It may take a day or so. Good luck.
Well, I am not aware of a compile time check but I do not think it is possible because how can the compiler know which value will be passed to the constructor (In case the value of your enum variable is calculated in runtime (e.g. by an If clause) ?
This can only be validated on runtime by using a validator method as you implemented for the enum types.
Example :
If in your code you have something like this :
EnumType1 enumVal;
if (<some condition>) {
enumVal = EnumType2.VALUE_SIX;
} else {
enumVal = EnumType2.VALUE_ONE;
}
There is no way the compiler can know which of the values will be assigned to enumVal so it won't be able to verify what is passed to the constructor until the if block is evaluated (which can be done only in runtime)

Categories