Python-like decorators in Java? [duplicate]
I spend most of my time programming in Python, so forgive me if my approach to this problem is short-sited:
I want to have certain methods of a class require login credentials. Simply, each method should check whether the class variable user
is set, and if so, continue, but if not, spit out a "you need to login" message.
In Python, I would just write a decorator to do this. How can I accomplish the same thing in java with as little redundant code as possible?
Thanks!
One way to solve this in Java is to use an Aspect-oriented programming tool. One such tool is AspectJ. You will probably find that this type of problem is an example that is commonly used to motivate AOP.
AOP might be a pretty heavyweight way to solve this particular problem, so you may want to explore just adding appropriate checks to each method. There isn't any direct equivalent to Python's decorators in native Java.
The simplest thing to do is to write a method like "assertCredentials" and call that method at the start of every method that needs credentials. If credentials are not set, the method should throw an exception, which will abort the parent method.
Java has annotations that can be used to decorate methods, etc., but I don't think using annotations in this case would simplify things.
You can try Google Guice AOP which is relatively more lightweight than AOP framework like AspectJ.
精彩评论