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

前端 未结 4 529
庸人自扰
庸人自扰 2020-12-23 16:03

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

4条回答
  •  死守一世寂寞
    2020-12-23 16:56

    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.

提交回复
热议问题