Results 1 to 3 of 3
  1. #1
    Roobiks is offline Member
    Join Date
    Mar 2016
    Posts
    19
    Rep Power
    0

    Question How to get access to annotation in class

    Hello there!

    I have a class with the following content:

    Java Code:
    public @interface todo {
    
        String what();
        int when();
    }
    I have a dummyClass with the following content:

    Java Code:
    @todo(what="This and That",when=12)
    public class dummyClass{
    	
    @todo(what="This and That",when=12)
    public void jump(int a){	..... }
    
    ......
    
    }
    And I have another class. In this class I want to check whether there is an annotation in dummyClass or not. If there is one I want to print it out via
    System.out.print.

    Can anypone help please?

    Thank you!
    Last edited by Roobiks; 04-04-2016 at 10:35 AM.

  2. #2
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,991
    Rep Power
    8

    Default Re: How to get access to annotation in class

    The Retention is important here.

    Java Code:
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    
    @Todo(what="Todo item", when=4)
    public class AnnotationTest {
    
        public static void main(String[] args) {
            AnnotationTest test = new AnnotationTest();
            Todo todo = test.getClass().getAnnotation(Todo.class);
            if (todo != null) {
                System.out.println(todo.what());
                System.out.println(todo.when());
            }
        }
    }
    
    @Retention(RetentionPolicy.RUNTIME)
    @interface Todo {
        String what();
        int when();
    }
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  3. #3
    Roobiks is offline Member
    Join Date
    Mar 2016
    Posts
    19
    Rep Power
    0

Similar Threads

  1. How to access a variable in one class from another?
    By Snake006 in forum New To Java
    Replies: 45
    Last Post: 07-19-2013, 08:29 PM
  2. Access ArrayList from another class!!!
    By hassaanid2012 in forum New To Java
    Replies: 7
    Last Post: 04-15-2012, 03:00 PM
  3. How to access an ArrayList in another class?
    By Alpa in forum New To Java
    Replies: 9
    Last Post: 12-30-2011, 11:30 PM
  4. Replies: 9
    Last Post: 07-17-2011, 09:24 AM
  5. Replies: 0
    Last Post: 04-04-2010, 10:06 AM

Posting Permissions

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