Results 1 to 3 of 3
  1. #1
    gunitinug is offline Member
    Join Date
    Dec 2016
    Posts
    13
    Rep Power
    0

    Default Java Reflection question

    Java Code:
    @MyAnnotation(name="someName",  value = "Hello World")
    public class TheClass {
    }
    
    
    
    
    public @interface MyAnnotation {
    	String   value();
            String   name();
    }
    
    
    
    import java.lang.annotation.Annotation;
    
    public class Test {
    
    	public static void main(String[] args) {		
    		Class aClass = TheClass.class;
    		Annotation annotation = aClass.getAnnotation(MyAnnotation.class);		
    		
    		if(annotation instanceof MyAnnotation){
    		    MyAnnotation myAnnotation = (MyAnnotation) annotation;
    		    System.out.println("name: " + myAnnotation.name());
    		    System.out.println("value: " + myAnnotation.value());
    		}
    	}
    
    }
    I'm expecting output:
    name: someName
    value: Hello World

    but I get nothing.
    Last edited by gunitinug; 11-01-2017 at 06:45 AM.

  2. #2
    gunitinug is offline Member
    Join Date
    Dec 2016
    Posts
    13
    Rep Power
    0

    Default Re: Java Reflection question

    Removing the if loop throws NullPointerException which leads me to belive that annotation is not assigned.

  3. #3
    gunitinug is offline Member
    Join Date
    Dec 2016
    Posts
    13
    Rep Power
    0

    Default Re: Java Reflection question

    Java Code:
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    
    @Retention(RetentionPolicy.RUNTIME)
    public @interface MyAnnotation {
    	String   value();
        String   name();
    }
    This fixed it.

Similar Threads

  1. Java Reflection
    By Nazneen Ali in forum New To Java
    Replies: 2
    Last Post: 10-11-2013, 12:23 PM
  2. Java Reflection API
    By Nirmitha in forum Advanced Java
    Replies: 3
    Last Post: 09-20-2013, 08:13 AM
  3. how to use java.reflection with parameter(s)
    By newbiejava in forum New To Java
    Replies: 8
    Last Post: 08-25-2010, 09:21 AM
  4. Java reflection: find serializable classes in package
    By andrew222 in forum Advanced Java
    Replies: 2
    Last Post: 02-27-2010, 07:36 AM
  5. Array Reflection: Multi Array Reflection
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-23-2008, 08:08 PM

Tags for this Thread

Posting Permissions

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