• Post Reply Bookmark Topic Watch Topic
  • New Topic

Enum RetentionPolicy  RSS feed

 
Dave Wagner
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can somebody explain the real-life need for @Retention(RetentionPolicy.RUNTIME) is? I looked at the javadoc which explains what it does but not why I will ever need it.

Thanks
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The RetentionPolicy pertains to Annotations, which provides a sort of meta-data about your code. To learn more about Annotations read The Annotations Tutorial.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
With @Retention(RetentionPolicy.RUNTIME), the annotation is preserved during runtime, and can be retrieved using reflection. You could use this for instance for testing purposes. Suppose you have an annotation called @Test that indicates a method is a test method. Then you could write an automatic testing tool:
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Quite a few libraries now work by looking at annotations - JUnit 4 (which is somewhat like what Rob mentions), but also APIs like JAX-WS and JAX-RS, and frameworks like Stripes. It cuts down on the number of config files that were traditionally used to keep this kind of information.

RetentionPolicy.SOUCE is useful for tools handling just the source code (like the javac compiler); @Override is an example of that.

What I don't understand is why RetentionPolicy.CLASS is the default; it seems less useful than the other two options.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!