开发者

toString() method is not overridden when a reference to Annotation is output in println() [closed]

开发者 https://www.devze.com 2023-03-13 20:19 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. 开发者_如何学编程 Closed 11 years ago.
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().

0

精彩评论

暂无评论...
验证码 换一张
取 消