java注解反射
我有一个java类,对于某些字段(不是所有字段),我将为该字段添加注释。现在,我想找到所有有注释的字段?
我知道,我可以迭代所有字段,并查找该字段是否有注释。 由于只有一两个字段有注释,所以我想要一种快速的方法来找到这样的注释字段。
I have a java class, for some field (not all field), I will put an annotation for the filed. Now, I would like to find all the fields which have annotation?
I know, I can iterate all fields, and find whether the field has annotation.
Since there is only one or two field has annotation, so I would like a quick method to find such annotated field.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不知道有什么方法比遍历所有字段更快。考虑到其他任何事情都需要其他一些代码来首先迭代所有字段,并以更适合您的用例的形式存储注释 - 这对于所有注释肯定没有用 -我不指望会为你提供任何东西。
您是否对遍历字段的速度进行了基准测试,发现它太慢了?如果您只是偶尔需要这样做,那么它可能已经足够快了。如果您需要在同一个类上多次执行此操作,那么您可以自己为此创建一个缓存,因此您只需要迭代任何特定类的字段一次。
I don't know any way quicker than iterating over all the fields. Given that anything else would require some other piece of code to iterate over all the fields first and store the annotations in a form more optimized for your use case - which certainly won't be useful for all annotations - I wouldn't expect there to be anything provided for you.
Have you benchmarked the speed of just iterating over the fields, and found it too slow? If you only need to do this occasionally, it's probably fast enough as it is. If you need to do it multiple times on the same class, then you can create a cache for this yourself, so you only ever need to iterate over the fields of any particular class once.