Annotation member which holds other annotations? - java

I want to create a custom annotation (using Java) which would accept other annotations as parameter, something like:
public #interface ExclusiveOr {
Annotation[] value();
}
But this causes compiler error "invalid type for annotation member".
Object[] also doesn't work.
Is there a way to do what I want?

The error is produced because you can't use interfaces as annotation values (change it to Comparable and you'll get the same error). From the JLS:
It is a compile-time error if the return type of a method declared in an annotation type is any type other than one of the following: one of the primitive types, String, Class and any invocation of Class, an enum type, an annotation type, or an array of one of the preceding types. It is also a compile-time error if any method declared in an annotation type has a signature that is override-equivalent to that of any public or protected method declared in class Object or in the interface annotation.Annotation.
I'm afraid I don't know of a good workaround, but now at least you know why you get the error.

Depending on the reason why you would want to specify other annotations there are multiple solutions:
An array of instances of a single annotation type
Probably not what you meant in your question, but if you want to specify multiple instances of a single annotation type it's certainly possible:
public #interface Test {
SomeAnnotation[] value();
}
An array of annotation types instead of instances
If you do not need to specify any parameters on the individual annotations you can just user their class objects instead of instances.
public #interface Test {
Class<? extends Annotation>[] value();
}
But an enum would of course also do the trick in most situations.
Use multiple arrays
If the set of possible annotation types you want to use is limited, you can create a separate parameter for each one.
public #interface Test {
SomeAnnotation[] somes() default { };
ThisAnnotation[] thiss() default { };
ThatAnnotation[] thats() default { };
}
Giving a default value to each member makes it possible to only specify arrays for the types you need.

You can do:
Class<? extends Annotation>[] value();
Not sure if that helps, but . . .

I myself hereby propose a workaround for the given problem:
Well, what I wanted to make possible was something like that:
#Contract({
#ExclusiveOr({
#IsType(IAtomicType.class),
#Or({
#IsType(IListType.class),
#IsType(ISetType.class)
})
})
})
Proposed workaround:
Define a class with parameter-less constructor (which will be called by your own annotation processor later) in following way:
final class MyContract extends Contract{
// parameter-less ctor will be handeled by annotation processor
public MyContract(){
super(
new ExclusiveOr(
new IsType(IAtomicType.class),
new Or(
new IsType(IListType.class),
new IsType(ISetType.class)
)
)
);
}
}
usage:
#Contract(MyContract.class)
class MyClass{
// ...
}

I just ran into this exact problem, but (inspired by #ivan_ivanovich_ivanoff) I have discovered a way to specify a bundle of any combination of Annotations as an annotation member: use a prototype / template class.
In this example I define a WhereOr (i.e. a "where clause" for my model annotation) which I need to contain arbitrary Spring meta-annotations (like #Qualifier meta-annotations).
The minor (?) defect in this is the forced dereferencing that separates the implementation of the where clause with the concrete type that it describes.
#Target({})
#Retention(RetentionPolicy.RUNTIME)
public #interface WhereOr {
Class<?>[] value() default {};
}
#Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
#Retention(RetentionPolicy.RUNTIME)
public #interface JsonModel {
Class<?> value();
WhereOr where() default #WhereOr;
}
public class Prototypes {
#Qualifier("myContext")
#PreAuthorize("hasRole('ROLE_ADMINISTRATOR')")
public static class ExampleAnd {
}
}
#JsonModel(
value = MusicLibrary.class,
where = #WhereOr(Prototypes.ExampleAnd.class)
)
public interface JsonMusicLibrary {
#JsonIgnore
int getMajorVersion();
// ...
}
I will programmatically extract the possible valid configurations from the "where clause" annotation. In this case I also use the prototypes class as a logical AND grouping and the array of classes as the logical OR.

Related

How to force annotations to have an "id" field?

I have the following annotation:
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.METHOD)
public #interface IdentifiableMethod {
String id() default "";
}
I will have to loop through a list of annotations and for each of them, perform a annotation.id().
Hence, I would have liked to use this "base" annotation to make it extended by other annotations:
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.METHOD)
public #interface SpecificMethod extends IdentifiableMethod{
//invalid: annotation cannot have extends list
}
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.METHOD)
public #interface OtherSpecificMethod extends IdentifiableMethod{
//invalid: annotation cannot have extends list
}
... and then generically access the .id() method in a loop by getting in parameter a List<A extends IdentifiableMethod>, so that the compiler always makes me access that method.
However, I've just found out that in the Java specification, all Java annotations extend natively the interface Annotation and they cannot have an extends list [Source: this Stack Overflow question and its answers].
Is there any way to reach something similar?
Just to clarify the need, I need to get all the methods of all the classes within my package by reflection and scan for these annotations. They may be different (they may have more or less properties, different usages etc.), but they all need to have a String id field:
List<Class<?>> classes = getClasses(packageName);
for (Class<?> clazz : classes) {
for (Method method : clazz.getMethods()) {
for (Class<A> annotation : annotations) { //<-- annotations is a Collection<Class<A extends Annotation>>
if (method.isAnnotationPresent(annotation)) {
A targetAnnotation = method.getAnnotation(annotation);
String id = targetAnnotation.id(); //<-- this is not valid because A extends Annotation, not IdentifiableMethod
//rest of code (not relevant)
}
}
}
}
P.s. I already did this but I was looking for something cleaner:
String id = targetAnnotation.getClass().getMethod("id").invoke(targetAnnotation).toString();

#Inherited annotation is not being inherited

I have a SubClass and a SuperClass, as well as an annotation DocAnnotation. I need a call to SubClass.foo() to get all class annotations from SubClass and SuperClass. The classes are defined like this:
SuperClass
package Code
import Annotations.DocAnnotation;
import java.util.Arrays;
#DocAnnotation("Super Annotation")
public class SuperClass {
public void foo() {
System.out.println(Arrays.toString(this.getClass().getAnnotations()));
System.out.println(Arrays.toString(this.getClass().getDeclaredAnnotations()));
}
}
SubClass
package Code;
import Annotations.DocAnnotation;
#DocAnnotation("Sub Annotation")
public class SubClass extends SuperClass{
}
DocAnnotation
package Annotations;
import java.lang.annotation.Inherited;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
#Inherited
#Retention(RetentionPolicy.RUNTIME)
#Repeatable(DocAnnotations.class)
public #interface DocAnnotation {
String value();
}
Running SubClass.foo I expect to see both "Super Annotation" and "Sub Annotation" but instead I see only [#Annotations.DocAnnotation(value=Sub Annotation)]. Am I misunderstanding what #inherited does, or am I doing something incorrectly?
Edit:
After adding the annotation #DocAnnotation("Super Annotation") to SubClass (that's the same one as in SuperClass) it actually shows up twice, once for its use in SubClass and once for its use in SuperClass! Now I'm nearly certain I'm misunderstanding something...
This seems to be the intended behavior, or at least it's specified to work this way (doc):
If [...] the user queries the annotation type on a class declaration, and the class declaration has no annotation for this type, then the class's superclass will automatically be queried for the annotation type.
In other words, since SubClass is already annotated with #DocAnnotation, the superclass is not queried.
On further inspection, the behavior seems a bit weird, though, especially after experimenting with presence of the containing annotation type. I came up with the following example which illustrates this (link):
import java.lang.annotation.*;
import java.util.*;
#Inherited
#Repeatable(Container.class)
#Retention(RetentionPolicy.RUNTIME)
#interface Ann {
String value();
}
#Inherited
#Retention(RetentionPolicy.RUNTIME)
#interface Container {
Ann[] value();
}
// Basic case. Result is that
// only #Ann("2") is present on
// ExhibitASub.
#Ann("1")
class ExhibitASuper {
}
#Ann("2")
class ExhibitASub extends ExhibitASuper {
}
// Because this case results in the
// #Container being present on ExhibitBSuper,
// rather than #Ann, all three annotations
// end up appearing on ExhibitBSub.
#Ann("1")
#Ann("2")
class ExhibitBSuper {
}
#Ann("3")
class ExhibitBSub extends ExhibitBSuper {
}
// Similar to the preceding case, by
// forcing the use of #Container, both
// annotations are present on ExhibitCSub.
#Container(#Ann("1"))
class ExhibitCSuper {
}
#Ann("2")
class ExhibitCSub extends ExhibitCSuper {
}
// Yet when we force both to use #Container,
// only #Container(#Ann("2")) is present on
// ExhibitDSub.
#Container(#Ann("1"))
class ExhibitDSuper {
}
#Container(#Ann("2"))
class ExhibitDSub extends ExhibitDSuper {
}
class Main {
public static void main(String[] args) {
for (Class<?> cls : Arrays.asList(ExhibitASub.class,
ExhibitBSub.class,
ExhibitCSub.class,
ExhibitDSub.class)) {
System.out.printf("%s:%n", cls);
for (Annotation ann : cls.getAnnotations()) {
System.out.printf(" %s%n", ann);
}
System.out.println();
}
}
}
The output of which is as follows:
class ExhibitASub:
#Ann(value=2)
class ExhibitBSub:
#Container(value=[#Ann(value=1), #Ann(value=2)])
#Ann(value=3)
class ExhibitCSub:
#Container(value=[#Ann(value=1)])
#Ann(value=2)
class ExhibitDSub:
#Container(value=[#Ann(value=2)])
Note that for B and C we see both the annotations on the superclass and subclass. Presumably this is because (in a strict sense) the annotation present on the superclass is of a different type than the annotation present on the subclass. Note that for D we return to only seeing the subclass annotation because both classes use the container type.
Using the containing annotation type explicitly could be a workaround for some cases, but it's not a general solution because of case D.
I might file a bug report for this tomorrow since this seems pretty undesirable. Since #Inherited predates #Repeatable, this behavior could be from previous versions where this situation couldn't occur.
You are getting this annotation wrong. The javadoc clearly states:
Indicates that an annotation type is automatically inherited. If an Inherited meta-annotation is present on an annotation type declaration, and the user queries the annotation type on a class declaration, and the class declaration has no annotation for this type, then the class's superclass will automatically be queried for the annotation type.
In other words: if you query the subclass, then you would find the super class being annotated. But this thing is not meant for inheritance in the "OO sense". If you want to see both annotations, you have to write code that checks each class in the class inheritance tree manually.

Use #Parameters in TestNg on class level

The #Parameters annotation implementation from org.testng.annotations looks like this:
#Retention(RetentionPolicy.RUNTIME)
#Target({ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.TYPE})
public #interface Parameters {
String[] value() default {};
}
So, it should allow me to use it on a ElementType.TYPE => it could also be used on a class.
When I use it on a method, I simply take the value using:
#Parameters("value")
public void m(String value) {
...
}
But if I use
#Parameters("value")
public class A {
...
}
how can I get the value inside the class?
If you want to use it for initialising class variables you can put in on constructor of class and use it.
ElementType.TYPE also means applicable to interfaces and enums - may be that one is specified if you want to extend the annotation.

Java Generics .class

We have an annotation #Accepts:
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.FIELD)
public #interface Accepts {
Class[] value();
}
It takes a list of Classes. These are later used to validate in a DSL that a field was passed an instance of the classes listed as acceptable.
Some examples of this annotation in use:
public enum PropertyName {
#Accepts({Integer.class})
xCoordinate,
#Accepts({Integer.class})
yCoordinate,
#Accepts({Boolean.class})
showPermission
#Accepts({String.class, FieldScript.class, List.class})
onClick
/* And So On*/
}
I am adding a new item to this enum called 'value' and it can accept a String or a PropertyResolver. PropertyResolver is an interface defined as below:
public interface PropertyResolver<T> {
public T getValue(TagContext tagContext);
}
I don't know how to do a .class on PropertyResolver to pass on to #Accepts. Is it possible to do so?
Thanks.
You will have to do PropertyResolver.class. There will only one Class instance that represents the the class (raw-version).
No such things as PropertyResolver<T>.class or PropertyResolver<Integer>.class exist.
Always, keep in mind that in Java, generics is compile time only feature.

Enum default value for Java enum annotation value

Java allows enum as values for annotation values. How can I define a kind of generic default enum value for an enum annotation value?
I have considered the following, but it won't compile:
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.FIELD)
public <T extends Enum<T>> #interface MyAnnotation<T> {
T defaultValue();
}
Is there a solution to this issue or not?
BOUNTY
Is does not seem like there is a direct solution to this Java corner case. So, I am starting a bounty to find the most elegant solution to this issue.
The ideal solution should ideally meet the following criteria:
One annotation reusable on all enums
Minimum effort/complexity to retrieve the default enum value as an enum from annotation instances
BEST SOLUTION SO FAR
By Dunes:
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.FIELD)
public #interface MyAnnotation {
// By not specifying default,
// we force the user to specify values
Class<? extends Enum<?>> enumClazz();
String defaultValue();
}
...
public enum MyEnumType {
A, B, D, Q;
}
...
// Usage
#MyAnnotation(enumClazz=MyEnumType.class, defaultValue="A");
private MyEnumType myEnumField;
Of course, we can't force the user to specify a valid default value at compile time. However, any annotation pre-processing can verify this with valueOf().
IMPROVEMENT
Arian provides an elegant solution to get rid of clazz in annotated fields:
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.FIELD)
public #interface MyAnnotation {
}
...
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.FIELD)
#MyAnnotation()
public #interface MyEnumAnnotation {
MyEnumType value(); // no default has user define default value
}
...
#MyEnumAnnotation(MyEnum.FOO)
private MyEnumType myValue;
The annotation processor should search for both MyEnumAnnotation on fields for the provided default value.
This requires the creation of one annotation type per enum type, but guarantees compile time checked type safety.
Not entirely sure what you mean when you say get a default value if said value wasn't provided in the constructor args, but not be caring about the generic type at runtime.
The following works, but is a bit of an ugly hack though.
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
public class Main {
#MyAnnotation(clazz = MyEnum.class, name = "A")
private MyEnum value;
public static v oid main(String[] args) {
new Main().printValue();
}
public void printValue() {
System.out.println(getValue());
}
public MyEnum getValue() {
if (value == null) {
value = getDefaultValue("value", MyEnum.class);
}
return value;
}
private <T extends Enum<?>> T getDefaultValue(String name, Class<T> clazz) {
try {
MyAnnotation annotation = Main.class.getDeclaredField(name)
.getAnnotation(MyAnnotation.class);
Method valueOf = clazz.getMethod("valueOf", String.class);
return clazz.cast(valueOf.invoke(this, annotation.value()));
} catch (SecurityException e) {
throw new IllegalStateException(e);
} catch (NoSuchFieldException e) {
throw new IllegalArgumentException(name, e);
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
} catch (NoSuchMethodException e) {
throw new IllegalStateException(e);
} catch (InvocationTargetException e) {
if (e.getCause() instanceof RuntimeException) {
throw (RuntimeException) e.getCause();
/* rethrow original runtime exception
* For instance, if value = "C" */
}
throw new IllegalStateException(e);
}
}
public enum MyEnum {
A, B;
}
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.FIELD)
public #interface MyAnnotation {
Class<? extends Enum<?>> clazz();
String name();
}
}
edit: I changed the getDefaultValue to work via the valueOf method of enums, thus giving a better error message if the value given is not reference instance of the enum.
I'm not sure what your use case is, so I have two answers:
Answer 1:
If you just want to write as little code as possible, here is my suggestion extending Dunes' answer:
public enum ImplicitType {
DO_NOT_USE;
}
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.FIELD)
public #interface MyAnnotation {
Class<? extends Enum<?>> clazz() default ImplicitType.class;
String value();
}
#MyAnnotation("A");
private MyEnumType myEnumField;
When clazz is ImplicitType.class, use the fields type as enum class.
Answer 2:
If you want to do some framework magic and want to maintain compiler checked type safety, you can do something like this:
/** Marks annotation types that provide MyRelevantData */
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.ANNOTATION_TYPE)
public #interface MyAnnotation {
}
And in the client code, you would have
/** Provides MyRelevantData for TheFramework */
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.FIELD)
#MyAnnotation
public #interface MyEnumAnnotation {
MyEnumType value(); // default MyEnumType.FOO;
}
#MyEnumAnnotation(MyEnum.FOO)
private MyEnumType myValue;
In this case you would scan the field for annotations which again are annotated with MyAnnotation. You will have to access the value via reflection on the annotation object, though. Seems like this approach is more complex on the framework side.
Simply put, you can not do that. Enums can not easily be used as generic types; with perhaps one exception, which is that Enums can actually implement interfaces which allows somewhat dynamic usage. But that won't work with annotations as set of types that can be used is strictly limited.
Your generic type syntax is a little off. It should be:
public #interface MyAnnotation<T extends Enum<T>> {...
but compiler gives error:
Syntax error, annotation declaration cannot have type parameters
Nice idea. Looks like it's not supported.
Frameworks using annotations can really profit from using apt. It's a preprocesor contained in javac, which will let you analyse declarations and their annotations (but not local declarations inside methods).
For your problem you would need to write an AnnotationProcessor (a class used as starting point for preprocessing) to analyse the annotation by using the Mirror API. Actually Dunes' annotation is pretty close to what is needed here. Too bad enum names aren't constant expressions, otherwise Dunes' solution would be pretty nice.
#Retention(RetentionPolicy.SOURCE)
#Target(ElementType.FIELD)
public #interface MyAnnotation {
Class<? extends Enum<?>> clazz();
String name() default "";
}
And here's an example enum: enum MyEnum { FOO, BAR, BAZ, ; }
When using a modern IDE, you can display errors on directly on the annotation element (or the annotation's value), if the name isn't a valid enum constant. You can even provide auto complete hints, so when a user writes #MyAnnotation(clazz = MyEnum.class, name = "B") and hits the hotkeys for auto-completion after writing B, you can provide him a list to choose from, containing all the constants starting with B: BAR and BAZ.
My suggestion to implement the default value is to create a marker annotation to declare an enum constant as default value for that enum. The user would still need to provide the enum type, but could omit the name. There are probably other ways though, to make a value the default one.
Here's a tutorial about apt and here the AbstractProcessor which should be extended to override the getCompletions method.
My suggestion is similar to kapep's suggestion. The difference is that I propose using the annotation processor for code creation.
A simple example would be if you intended to use this only for enums that you yourself wrote. Annotate the enum with a special enum. The annotation processor will then generate a new annotation just for that enum.
If you work with a lot of enums that you did not write, then you could implement some name mapping scheme: enum name -> annotation name. Then when the annotation processor encountered one of these enums in your code, it would generate the appropriate annotation automatically.
You asked for:
One annotation reusable on all enums ... technically no, but I think the effect is the same.
Minimum effort/complexity to retrieve the default enum value as an enum from annotation instances ... you can retrieve the default enum value without any special processing
I had a similar need and came up with the following pretty straightforward solution:
The actual #Default interface:
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.FIELD)
public #interface Default {}
Usage:
public enum Foo {
A,
#Default B,
C;
}
Finding the default:
public abstract class EnumHelpers {
public static <T extends Enum<?>> T defaultEnum(Class<T> clazz) {
Map<String, T> byName = Arrays.asList(clazz.getEnumConstants()).stream()
.collect(Collectors.toMap(ec -> ec.name(), ec -> ec));
return Arrays.asList(clazz.getFields()).stream()
.filter(f -> f.getAnnotation(Default.class) != null)
.map(f -> byName.get(f.getName()))
.findFirst()
.orElse(clazz.getEnumConstants()[0]);
}
}
I've also played around with returning an Optional<T> instead of defaulting to the first Enum constant declared in the class.
This would, of course, be a class-wide default declaration, but that matches what I need. YMMV :)

Categories

Resources