gre*_*erd 7 java reflection methods
我知道你可以在Java中使用反射来获取运行时类,方法,字段等的名称.我想知道一个方法可以找到自己的名字,而它的内部是自己的吗?另外,我也不想将方法的名称作为String参数传递.
例如
public void HelloMyNameIs() {
String thisMethodNameIS = //Do something, so the variable equals the method name HelloMyNameIs.
}
Run Code Online (Sandbox Code Playgroud)
如果这是可能的,我认为它可能涉及使用反射,但也许它不会.
如果有人知道,我们将不胜感激.
使用:
public String getCurrentMethodName()
{
StackTraceElement stackTraceElements[] = (new Throwable()).getStackTrace();
return stackTraceElements[1].toString();
}
Run Code Online (Sandbox Code Playgroud)
在你希望获得名称的方法里面.
public void HelloMyNameIs()
{
String thisMethodNameIS = getCurrentMethodName();
}
Run Code Online (Sandbox Code Playgroud)
(不是反思,但我认为不可能.)
这个单线程使用反射:
public void HelloMyNameIs() {
String thisMethodNameIS = new Object(){}.getClass().getEnclosingMethod().getName();
}
Run Code Online (Sandbox Code Playgroud)
缺点是代码无法移动到单独的方法.