为什么Java注释? [英] Why java annotations?

查看:222
本文介绍了为什么Java注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要问为什么用了这么多的Java注解......我知道他们更换xml配置在例如JPA,但为什么在所有使用这种配置?
考虑这块code的:

i want to ask why are the java annotations used so much... I know that they replaced xml configuration in for example jpa, but why is this kind configuration used at all? Consider this piece of code:

@Entity 
class Ent{
   // some fields
}
//... somewhere in the other file far far away
class NonEnt{
   // whatever here
}

现在,当我试图把这个持久化上下文,用的EntityManager 的persist方法,我得到运行时错误(最好是拿到编译错误),试图坚持 NonEnt 实例。这里对我来说是显而易见的解决方案,迫使实体来实现,而不是使用@Annotations一些没有方法接口。但是,这不是框架设计者中流行,这是什么解决方案的缺点?

谢谢回答...

Now, when I try to put this in persistence context, with EntityManager's persist method, I get runtime error(better would be to get compile error) with trying to persist NonEnt instance. There is obvious solution for me, force the entities to implement some no-method interface instead of using @Annotations. But this isn't popular among framework designer, what is the drawback of this solution?
Thanks for answering...

推荐答案

在比较标记接口,标注有一些优势:

When compared to marker interfaces, annotations have some advantages:


  • 它们可以参数

  • 他们更细粒度 - 你可以将它们附加不仅类,但也给其他类元素(字段,方法,方法参数等)

  • they can be parameterized
  • they are more fine grained - you can attach them not only to classes but also to other class elements (fields, methods, method arguments, etc)

注解,也理应侵扰程度较低,但该点是口味和有争议的问题。

Annotations are also supposedly less intrusive, but this point is matter of taste and debatable.

另请参阅:

  • Annotations (official JDK documentation)
  • What is the use of marker interfaces in Java?

这篇关于为什么Java注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆