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!
There isn't any direct equivalent to Python's decorators in native Java.
In terms of look and feel, python decorators can be considered similar to Java annotations, but under the hood, they work very very similar to the way Aspects work in Java. python decorators can only be specified on class and function declaration while you may annotate a field using java annotations.
Decorator is a structural pattern that allows adding new behaviors to objects dynamically by placing them inside special wrapper objects, called decorators. Using decorators you can wrap objects countless number of times since both target objects and decorators follow the same interface.
There is no relation between @override in Java and @decorator in Python. @override in Java is an annotation which marks a method as overwriting another method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With