将方法参数作为Java 8中的注解参数。

huangapple go评论69阅读模式
英文:

Take method argument as an argument in the annotation in Java 8

问题

迄今为止,我已经查找了,似乎不可能实现,所以如果是这种情况,那么满足以下要求的最佳替代方案是什么?

@Authentication_Annotation(id, password)
public void method(String id, String password, String param) {
    // 如果ID和密码正确,则执行某些操作。
}

由于您具有Python背景,使用装饰器在Python中是可能的。在Java中,我们是否仍然可以实现这一点,而不需要每次需要提供身份验证的方法时都调用一个进行身份验证的方法?

英文:

I have looked up and till now it doesn't seem possible, so, if that's the case, what is the best alternative to meet the following requirement?

@Authentication_Annotation(id, password)
public void method(String id, String password, String param) {
    // Does something if ID and Password are correct.
}

Coming from a python background, this would have been possible using decorators.
Can we still do it in java, without calling a method that authenticates every time a method needs to be provided authentication?

答案1

得分: 1

你可以直接在你的注解中访问方法参数,而不必将其明确地作为参数传递。

使用AOP:
https://stackoverflow.com/questions/15660535/get-method-arguments-using-spring-aop

无论如何,还可以通过反射使用DynamicProxy来实现另一种方式:
https://stackoverflow.com/questions/2541554/java-method-missing-ala-ruby-for-decorating

英文:

You can access method args directly in your annotation instead of passing it as arguments explicitly.

Using AOP:
https://stackoverflow.com/questions/15660535/get-method-arguments-using-spring-aop

Anyways there seems to be another way via reflection using DynamicProxy:
https://stackoverflow.com/questions/2541554/java-method-missing-ala-ruby-for-decorating

答案2

得分: 0

这在Java中是不可能的(至少不需要极端恶意的黑魔法)。

英文:

It is impossible in Java (at least without ungodly amount of very dark black magic).

huangapple
  • 本文由 发表于 2020年8月5日 17:53:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/63262663.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定