RetentionPolicy CLASS vs. RUNTIME

http://stackoverflow.com/questions/5971234/retentionpolicy-class-vs-runtime


RetentionPolicy CLASS vs. RUNTIME

What is the practical difference between RetentionPolicy.CLASS and RetentionPolicy.RUNTIME?

It looks like both are recorded into the bytecode and both may be accessed at the run-time anyway.

share | improve this question
 

1 Answer

up vote 6 down vote accepted

both may be accessed at the run-time anyway.

That's not what the javadoc says:

RUNTIME: Annotations are to be recorded in the class file by the compiler and retained by the VM at run time, so they may be read reflectively.

CLASS: Annotations are to be recorded in the class file by the compiler but need not be retained by the VM at run time.

In practice, I'm not aware of any use-cases for CLASS. It would only be useful if you wanted to read the bytecode programmatically, as opposed to via the classloader API, but that's a very specialised case, and I don't know why you wouldn't just use RUNTIME.

Ironically, CLASS is the default behaviour.

share | improve this answer
 
I read that of course. Sounds like "need not" does not exclude "may" That is why the question. –  Dima May 11 '11 at 22:17
 
@Dima: If the spec says an implementation doesn't have to do a thing, you'd be foolish to assume it does do that thing. Assume it doesn't. –  skaffman May 11 '11 at 22:18
 
You must be right. What is not clear is the meaning of words "implementation doesn't have to do a thing" for this rather specific case. At least as it is about RetentionPolicy.CLASS case I assume the implementation MUST keep information in the bytecode. Will anything stop me from extracting it from the bytecode using reflection? If yes (will stop) then what is the meaning of "keeping information in the bytecode"? –  Dima May 11 '11 at 22:23
3 
@Dima: You can extract it from the bytecode if you read the bytecode directly. If you use the reflection API, it likely won't be there. –  skaffman May 11 '11 at 22:24
 
That may be right. Not sure if existence of RetentionPolicy.CLASS makes much sense in this case. Maybe something more was behind it initially ... –  Dima May 11 '11 at 23:05
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值