Can a method figure out its own name using reflection in Java [duplicate]
I know that you can use reflection in Java to get the name of class, methods, fields...etc at run time. I was wondering can a method figure out its own name while its inside it's self? Also, I don't want to pass the name of the method as a String parameter either.
For example
public void HelloMyNameIs() {
String thisMethodNameIS = //Do something, so the variable equals the method name HelloMyNameIs.
}
If it that is possible, I was thinking it would probably involve using reflection, but maybe it doesn't.
If anybody know, it would be greatly appreciated.
Use:
public String getCurrentMethodName()
{
StackTraceElement stackTraceElements[] = (new Throwable()).getStackTrace();
return stackTraceElements[1].toString();
}
inside the method you want to get the name of.
public void HelloMyNameIs()
{
String thisMethodNameIS = getCurrentMethodName();
}
(Not reflection, but I don't think it is possible.)
This one-liner works using reflection:
public void HelloMyNameIs() {
String thisMethodNameIS = new Object(){}.getClass().getEnclosingMethod().getName();
}
The downside is that the code can't be moved to a separate method.
Using a Proxy all your methods (that override a method defined in an interface) can know their own names.
import java . lang . reflect . * ;
interface MyInterface
{
void myfun ( ) ;
}
class MyClass implements MyInterface
{
public void myfun ( ) { /* implementation */ }
}
class Main
{
public static void main ( String [ ] args )
{
MyInterface m1 = new MyClass ( ) ;
MyInterface m2 = ( MyInterface ) ( Proxy . newProxyInstance (
MyInterface . class() . getClassLoader ( ) ,
{ MyInterface . class } ,
new InvocationHandler ( )
{
public Object invokeMethod ( Object proxy , Method method , Object [ ] args ) throws Throwable
{
System . out . println ( "Hello. I am the method " + method . getName ( ) ) ;
method . invoke ( m1 , args ) ;
}
}
) ) ;
m2 . fun ( ) ;
}
}
Stack trace from current thread also:
public void aMethod() {
System.out.println(Thread.currentThread().getStackTrace()[0].getMethodName());
}
精彩评论