编写注解以防止参数无效时调用方法
我可以为一个方法添加一个注释,当它的参数为空时,什么都不做,实际上就像不被调用一样?
Can I have an annotation for a method that when its parameters are null, just do nothing, effectively as not being invoked?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
也许最简单的方法是使用接口和动态代理。注释除了添加元数据之外什么也不做。您必须添加代码才能根据注释进行操作。
您必须做一些事情 --
创建一个接口
使用实现时,将其实例化为 JDK 代理。
现在,您可以通过反射捕获
YourProxy
类中方法的所有调用。如果您不想这样做,那么您正在考虑更重量级的框架,例如 AspectJ / Spring AOP。
Probably the easiest way to do this is using interfaces and dynamic proxies. Annotations do nothing other than add metadata. You're going to have to add code to act based on the annotation.
You'd have to do a few things --
Create an interface
When using the implementation, instantiate it as a JDK Proxy.
Now, you can via reflection, capture all invocations of your method in
YourProxy
class.If you dont want to do this, then you're looking at more heavyweight frameworks such as AspectJ / Spring AOP.
注释本身只不过是数据。他们不“做”任何事情。您可以通过多种不同的方式拥有一个运行时框架来解释注释并完成您正在寻找的功能。最常见的技术是所谓的面向方面编程,您可以根据元数据更改程序组件的行为。
aspectJ 是一个功能齐全的库,它允许您更改几乎任何事物的行为!从技术上讲,您甚至不需要完整的方面注释,有很多不同的方法可以“匹配”您想要改变其行为的方法。
SpringAOP 是一个更有限的是aspectJ 提供的功能的子集,但它也更容易使用并添加到您的项目中!
Annotations in and of themselves are nothing but data. They don't "do" anything. There are a number of different ways you can have a run time framework that interprets annotations and accomplishes the functionality you're looking for. The most common technique would be what's called Aspect Oriented Programming, where you alter the behaviour of program components based on metadata.
aspectJ is a full featured library that allows you to change the behaviour of just about anything! You wouldn't even technically need an annotation will full aspectJ, there are lots of different ways to 'match' methods that you want to alter the behaviour of.
SpringAOP is a more limited subset of the functionality provided by aspectJ, but it is also easier to use and add to your project as a consequence!