gpt4 book ai didi

java - 请参阅有关调用方法的 java 注释

转载 作者:搜寻专家 更新时间:2023-10-31 08:10:18 26 4
gpt4 key购买 nike

假设我有这样的情况:

public String method(String s) {
return stringForThisVisibility(s, EnumVisibility.PUBLIC);
}

我想用这样的注释替换它:

@VisibilityLevel(value = EnumVisibility.PUBLIC)
public String method(String s) {
return stringForThisVisibility(s);
}

这似乎是一个更好、更清晰的解决方案,但我需要 stringForThisVisibility 方法通过某种反射来了解 @VisibilityLevel 的值。那可能吗?我可以看到调用 stringForThisVisibility 的方法上的注释吗?

最佳答案

有以下类:

 /**
* Proper use of this class is
* String testName = (new Util.MethodNameHelper(){}).getName();
* or
* Method me = (new Util.MethodNameHelper(){}).getMethod();
* the anonymous class allows easy access to the method name of the enclosing scope.
*/
public static class MethodNameHelper {
public String getName() {
final Method myMethod = this.getClass().getEnclosingMethod();
if (null == myMethod) {
// This happens when we are non-anonymously instantiated
return this.getClass().getSimpleName() + ".unknown()"; // return a less useful string
}
final String className = myMethod.getDeclaringClass().getSimpleName();
return className + "." + myMethod.getName() + "()";
}

public Method getMethod() {
return this.getClass().getEnclosingMethod();
}
}

可以调用: 方法我 = (new Util.MethodNameHelper(){}).getMethod();

我在该类(class)中大量使用了 getName() 调用。在我的机器上,那些匿名类实例化和方法调用往往每次花费大约 1500 ns。在我的性能测试中,StackElement 步行方法在我的机器上花费了大约 30 倍 (47000 ns)。

关于java - 请参阅有关调用方法的 java 注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8551287/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com