Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python-like decorators in Java? [duplicate]

Tags:

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!

like image 278
awegawef Avatar asked Dec 29 '10 04:12

awegawef


People also ask

Does Java have decorators like Python?

There isn't any direct equivalent to Python's decorators in native Java.

Is Java annotation same as Python decorator?

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.

What are decorators called in Java?

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.

Is @override a decorator in Java?

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.


2 Answers

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.

like image 142
Greg Hewgill Avatar answered Jan 14 '23 13:01

Greg Hewgill


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.

like image 24
Konstantin Komissarchik Avatar answered Jan 14 '23 11:01

Konstantin Komissarchik