开发者

Write annotation to guard a method from being called when parameters are invalid

开发者 https://www.devze.com 2023-03-29 01:35 出处:网络
Can I have an annotation for a me开发者_C百科thod that when its parameters are null, just do nothing, effectively as not being invoked?Probably the easiest way to do this is using interfaces and dynam

Can I have an annotation for a me开发者_C百科thod that when its parameters are null, just do nothing, effectively as not being invoked?


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

public interface IService {

     @ValidateNull // Your custom annotation
     public void yourMethod(String s1);
}

When using the implementation, instantiate it as a JDK Proxy.

IService myService = (IService)java.lang.Proxy.newInstance(ServiceImpl.class.getClassLoader(),
                           ServiceImpl.class.getInterfaces(), 
                           new YourProxy(new ServiceImpl());

Now, you can via reflection, capture all invocations of your method in YourProxy class.

 public YourProxy implements InvocationHandler {
public Object invoke(Object arg0, Method method, Object[] args) throws Throwable {
    if (method.isAnnotationPresent(ValidateNull.class)) {
                   //Check args if they are null and return.
            }
     }
 }

If you dont want to do this, then you're looking at more heavyweight frameworks such as AspectJ / Spring AOP.


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!

0

精彩评论

暂无评论...
验证码 换一张
取 消