Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a Python Decorator the same as Java annotation, or Java with Aspects?

Are Python Decorators the same or similar, or fundamentally different to Java annotations or something like Spring AOP, or Aspect J?

like image 945
bn. Avatar asked Mar 11 '13 19:03

bn.


People also ask

Is decorator same as annotation?

Annotations are only metadata set on the class using the Reflect Metadata library. Decorator corresponds to a function that is called on the class. Annotations are used for creating an attribute annotations that stores array. Decorator is a function that gets the object that needs to be decorated.

Does Java have decorators like Python?

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

What is a Python decorator?

A decorator is a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure. Decorators are usually called before the definition of a function you want to decorate.

What is decorator class in Python?

Decorators are a very powerful and useful tool in Python since it allows programmers to modify the behaviour of function or class. Decorators allow us to wrap another function in order to extend the behaviour of the wrapped function, without permanently modifying it.


1 Answers

Python decorators are just syntactic sugar for passing a function to another function and replacing the first function with the result:

@decorator def function():     pass 

is syntactic sugar for

def function():     pass function = decorator(function) 

Java annotations by themselves just store metadata, you must have something that inspects them to add behaviour.

 

Java AOP systems are huge things built on top of Java, decorators are just language syntax with little to no semantics attached, you can't really compare them.

like image 91
Pavel Anossov Avatar answered Sep 24 '22 15:09

Pavel Anossov