package javaapplication20;
import java.lang.annotation.*;
import java.lang.reflect.*;
@Retention (RetentionPolicy.RUNTIME)
@interface MyAnno {
String str();
int yu();
}
@Retention (RetentionPolicy.RUNTIME)
@interface Wasp {
double hg();
}
@MyAnno(str = "Falcon", yu=5 )
@Wasp(hg = 54.67)
public class Main {
@MyAnno(str = "Raptor", yu=7 )
@Wasp(hg = 90.56)
public static void meth(){
Main ob = new Main();
try{
Annotation annon[] = ob.getClass().getAnnotations();
System.out.println("All anotations for Main are ");
for(Annotation a : annon){
System.out.println(a);
}
Method m = ob.getClass().getMethod("meth");
Annotation annons[] = m.getAnnotations();
System.out.println("All Annotations for meth() are ");
for(Annotation a : annons){
System.out.println(a);
}
}catch(NoSuchMethodException e){
System.out.println("No Match Found");
}
}
public static void main(String[] args) {
meth();
}
}
OUTPUT :
All anotations for Main are
@javaapplication20.MyAnno(str=Falcon, yu=5)
@javaapplication20.Wasp(hg=54.67)
All Annotations for meth() are
@javaapplication20.MyAnno(str=Raptor, yu=7)
@javaapplication20.Wasp(hg=90.56)
This answer is hidden in the javaDoc of the Annotation
interface. For toString()
, it says:
Returns a string representation of this annotation. The details of the representation are implementation-dependent, but the following may be regarded as typical:
@com.acme.util.Name(first=Alfred, middle=E., last=Neuman)
And this is what you see on your output. The java compiler will create a class file for your annotation and this class file will have an implementation of toString()
that produces this output. Implementation-dependent refers to the java compiler, not to your implementation of an annotation.
I think your question is;
Does an @Annotation have a default implementation for toString()?
The answer is yes. It also has a default implementation for hashCode() and equals().
精彩评论