Java 中类似 Python 的装饰器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4551457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 06:54:45  来源:igfitidea点击:

Python-like decorators in Java?

javapython

提问by awegawef

I spend most of my time programming in Python, so forgive me if my approach to this problem is short-sited:

我大部分时间都用 Python 编程,所以如果我解决这个问题的方法很短,请原谅我:

I want to have certain methods of a class require login credentials. Simply, each method should check whether the class variable useris set, and if so, continue, but if not, spit out a "you need to login" message.

我想让某个类的某些方法需要登录凭据。简单来说,每个方法都应该检查类变量user是否设置,如果设置,则继续,如果没有,则吐出“您需要登录”的消息。

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?

在 Python 中,我只会编写一个装饰器来做到这一点。我怎样才能用尽可能少的冗余代码在 java 中完成同样的事情?

Thanks!

谢谢!

采纳答案by Greg Hewgill

One way to solve this in Java is to use an Aspect-oriented programmingtool. One such tool is AspectJ. You will probably find that this type of problem is an example that is commonly used to motivate AOP.

在 Java 中解决此问题的一种方法是使用面向方面的编程工具。其中一种工具是AspectJ。你可能会发现这类问题是一个常用来激励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.

AOP 可能是解决这个特定问题的一种非常重量级的方法,因此您可能想探索只为每个方法添加适当的检查。在原生 Java 中没有任何直接等同于 Python 的装饰器。

回答by Konstantin Komissarchik

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.

最简单的方法是编写一个像“assertCredentials”这样的方法,并在每个需要凭据的方法开始时调用该方法。如果未设置凭据,该方法应抛出异常,这将中止父方法。

Java has annotations that can be used to decorate methods, etc., but I don't think using annotations in this case would simplify things.

Java 具有可用于装饰方法等的注释,但我认为在这种情况下使用注释不会简化事情。

回答by Joshua Partogi

You can try Google Guice AOPwhich is relatively more lightweight than AOP framework like AspectJ.

您可以尝试Google Guice AOP,它比 AOP 框架(如 AspectJ)相对更轻巧。

回答by fastcodejava

You should look into bean validation framework.

您应该研究bean 验证框架