| Author |
Regarding Inherited Annotation
|
Ritesh Raman
Ranch Hand
Joined: Jun 20, 2005
Posts: 34
|
|
I am using following code to use Inherited Annotaion:
------TestAnnotation.java----------------------------------------------
import java.lang.annotation.Inherited;
@Inherited
public @interface TestAnnotation {
boolean isInherited() default true;
String doSomething() default "Do what?";
}
---------------------------------------------------------------------------
---------AnnotationChild.java------------------------------------------
@TestAnnotation
public class AnnotationChild {
public static void main(String [] args){
AnnotationChild ta = new AnnotationChild();
System.out.println("hello"+ta.doSomething());
}
}
--------------------------------------------------------------------------------
now i am getting compile time error.
The method doSomething() is undefined for the type AnnotationChild
i am not able to use the interface properties.
please guide where i m wrong.
Thanks
Ritesh
|
Thanks,<br />--------<br />SCJP 1.4
|
 |
Jesper de Jong
Java Cowboy
Bartender
Joined: Aug 16, 2005
Posts: 12956
|
|
|
Annotations are not on the SCJP exam, so your post does not belong in the SCJP forum. I will move it to a more appropriate forum for you.
|
Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19232
|
|
Annotation methods are not inherited this way. The annotation itself is inherited, and you can retrieve it using reflection. For example:
However, the values are the same for all instances of the class; you can't have one instance return false for isInherited() and another true.
This example requires regular interfaces:
Or, if you're lazy, use an abstract class in between:
I think you should read http://java.sun.com/docs/books/tutorial/java/javaOO/annotations.html, it may help you understand annotations better.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Ritesh Raman
Ranch Hand
Joined: Jun 20, 2005
Posts: 34
|
|
Hi Rob,
Can you please explain more below line (The annotation itself is inherited).how can Annotation methods are inherited ?
How can we use '@inherited'.if possible please explain with example:
!--Annotation methods are not inherited this way. [b]The annotation itself is inherited, and you can retrieve it using reflection. For example:
i have used the below line in our code , it give NullPointerException at the line no. 3. Pease explain:
1.Class<?> cls = ta.getClass();
2.TestAnnotation anno = cls.getAnnotation(TestAnnotation.class);
3.System.out.println(anno.doSomething()); --![/b]
Thanks
Ritesh
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19232
|
|
Ah, right. The retention policy defaults to RetentionPolicy.CLASS. You'll need to change your annotation a bit:
|
 |
 |
|
|
subject: Regarding Inherited Annotation
|
|
|