Results 1 to 3 of 3

Thread: Java Annotations

  1. #1
    Join Date
    May 2007
    Beans
    61
    Distro
    Ubuntu 7.04 Feisty Fawn

    Java Annotations

    I'm experimenting with annotations, and reflection in Java. This simple piece of code below, I would of thought would work. What I'm I doing wrong.

    Code:
    @interface Tag {}
    
    @Tag
    public class Main {
    
        public static boolean isTagged(Object o) {
            return o.getClass().isAnnotationPresent(Tag.class);
        }
        
        public static void main(String[] args) {
            System.out.println(isTagged(new Main()));
        }
    
    }
    I've greated an annotation call Tag applied it to the class Main, then written a function to check if the Tag annotation is present (isTagged). I'd expect to see true printed to STDOUT. But I'm getting "false". I'm sure this has to be somthing simple.

    Any help greatfully recieved. Thanks
    I have long messy hair, scruffy clothes and bang on about freedom as if I'd been in prison for the last 50 years -- I am of course a Free Software Advocate.

  2. #2
    Join Date
    Jun 2006
    Location
    The Netherlands
    Beans
    2,185
    Distro
    Ubuntu 12.04 Precise Pangolin

    Re: Java Annotations

    By default, annotations are thrown away by the compiler. You have to specify that your annotation should be retained in the class file by annotating your annotation with the @Retention annotation:
    Code:
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    
    @Retention(RetentionPolicy.RUNTIME)
    @interface Tag {}
    Ubuntu 12.04

  3. #3
    Join Date
    May 2007
    Beans
    61
    Distro
    Ubuntu 7.04 Feisty Fawn

    Re: Java Annotations

    Thank you so much I knew it had to be somthing simple. Thanks
    I have long messy hair, scruffy clothes and bang on about freedom as if I'd been in prison for the last 50 years -- I am of course a Free Software Advocate.

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •