Let's supposed i have this interface:
public interface MyInterface {
void doStuff();
}
With a concrete implementation:
public class HardCoreConcrete implements MyInterface {
void doStuff() {
// i really do stuff, honest
}
}
And suppose i have this annotation:
@Target(ElementType.class)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
Class<MyInterface> clazz;
}
It would be used like this:
@MyAnnotation(clazz = HardCoreConcrete.class)
public class SomeOtherClass {
...
}
Why does this not work? My compiler complains that for clazz it expected type MyInterface! But HardCoreConcrete implements MyInterface.
Am I doing something wrong? Is this not allowed? Am i out of luck?
Annotations can be applied to declarations: declarations of classes, fields, methods, and other program elements. When used on a declaration, each annotation often appears, by convention, on its own line. As of the Java SE 8 release, annotations can also be applied to the use of types.
Which of the following is not pre defined annotation in Java? Explanation: @Overriden is not a pre defined annotation in Java. @Depricated, @Override, @SuppressWarnings, @SafeVarags and @FunctionInterface are the pre defined annotations.
Type annotations can provide static verification when creating new objects to help enforce the compatibility of annotations on the object constructor. For example: Generics and arrays. Generics and arrays are great candidates for type annotations, because they can help restrict the data that is to be expected for these objects.
Any declaration can be marked with annotation by placing it above that declaration. As of Java 8, annotations can also be placed before a type. 1. Above declarations As mentioned above, Java annotations can be placed above class, method, interface, field, and other program element declarations.
AnnotationName is an identifier. The parameter should not be associated with method declarations and throws clause should not be used with method declaration. Parameters will not have a null value but can have a default value. default value is optional.
Type annotations can provide a stronger type-checking system, reducing the number of errors and bugs within code. Applications using type annotations are also backward compatible, because annotations do not affect runtime operation. Developers can opt to create custom type annotations, or use annotations from third-party solutions.
You need
public @interface MyAnnotation {
Class<? extends MyInterface> clazz;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With