Where The Streets Have No Name

호출한 메소드명 알아내기 본문

Developement/Java

호출한 메소드명 알아내기

highheat 2006. 7. 11. 14:54
/**
     * Get method name within the current call stack. The top most has offset 0 (that is this method), the next has offset 1
     * (that is the caller of this method), and so on.
     * Usage: <code>getMethodName(new Throwable())</code>.
     *
     * @param full If true, not only the method name but the complete package and class string as prefix
     * (e.g. "org.happy.tools.Utils.getLucky")
     * @param offset Index offset from top most stack trace element. If the caller wants to get the name of the
     * method of its caller, the offset has to be 2.
     * @return Method name of the top StackTraceElement.
     */

    static public String getMethodName(final boolean full, final int offset) {
        String result = null;
       
        final Throwable t = new Throwable();
        if (t != null) {
            final StackTraceElement[] stes = t.getStackTrace();
            if (stes != null && stes.length > 0) {
                if (full) {
                    result = stes[offset].getClassName().concat(".").concat(stes[offset].getMethodName());
                } else {
                    result = stes[offset].getMethodName();
                }
            }//else: StackTraceElement unavailable
        }//else: input unavailable
       
        return result;
    }//getMethodName()


사용법) System.out.println(HelloWorld.getMethodName(true,1)); //이부분이 코딩된 메소드명이 출력됨

public String getMethodName() {
  String result = null;
       
  final Throwable t = new Throwable();
  if (t != null) {
   final StackTraceElement[] stes = t.getStackTrace();
   if (stes != null && stes.length > 0) {
    result = stes[1].getClassName().concat(".").concat(stes[1].getMethodName());   
   }//else: StackTraceElement unavailable
  }//else: input unavailable
       
  return result;
 }//getMethodName()