简体   繁体   English

在Java中找到调用方法和类的名称

[英]In Java find name of calling method and class

One of my colleagues decided we needed to print each class and method as they are executed so he promptly typed in the name of each method and class at the start of each method. 我的一位同事认为我们需要在执行每个类和方法时打印它们,因此他迅速在每个方法的开头键入每个方法和类的名称。 This was not a little painful to me so I looked up on the web and came up with: 这对我来说并没有什么痛苦,所以我在网上查了一下结果:

System.out.println(new Object(){}.getClass().getEnclosingClass().getSimpleName()+ " : "+
    new Object(){}.getClass().getEnclosingMethod().getName() +" [IN]");

This works swell. 这行得通。 Except that now I have been informed that this is unsatisfactory because we are creating the Object for the sole purpose of finding the names and we should "Instead, simply use the class' .class property". 除了现在我被告知这是不令人满意的,因为我们仅出于查找名称的目的创建对象,而应该“相反,只需使用class的.class属性”。 Minor problem, I can't seem to get that to work. 次要问题,我似乎无法解决。

Something else I found on the web was: 我在网上发现的其他内容是:

System.out.println(Thread.currentThread().getStackTrace()[1].getClassName()  + " : "+
    Thread.currentThread().getStackTrace()[1].getMethodName() +" [IN]");

which does what I need but somebody suggested it was SLOW, having to do a stack trace. 这可以满足我的需要,但有人建议它很慢,必须执行堆栈跟踪。

Does anybody have any good suggestions? 有人有什么好的建议吗?

I noticed nobody answered the question, so I wrote something to time the two versions with a hard coded version as a control. 我注意到没有人回答这个问题,所以我写了一些东西来用硬编码版本作为控件来计时两个版本。 These functions were called a million times on a 2998 MHz, SPARC-T4 with 64 bit, Java 1.8.0_91. 这些功能在2998 MHz,64位SPARC-T4,Java 1.8.0_91上被称为百万次。

public String findFunc1()
{
    Class myCls=new Object(){}.getClass();

    String ret=myCls.getEnclosingClass().getSimpleName()+ " : "
              +myCls.getEnclosingMethod().getName()+ " [IN]";
    return ret;
}
public String findFunc2()
{
    StackTraceElement mySTE=Thread.currentThread().getStackTrace()[1];
    String ret=mySTE.getClassName() + " : "+ mySTE.getMethodName() + " [IN]";
    return ret;
}
public String findFunc3()
{
    String ret="TimeLog"+ " : "+ "findFunc3" + " [IN]";
    return ret;
}

They were called as follows: 他们被称为如下:

public static void time1() {
    System.out.print("new Object version ");
    long startTime = System.currentTimeMillis();
    String ret;
    TimeLog prog=new TimeLog();

    for(int ii=0; ii<1*1000*1000; ii++) {
        ret=prog.findFunc1();
    }
    long endTime   = System.currentTimeMillis();
    long totalTime = endTime - startTime;
    System.out.println("Elapsed msec="+totalTime);
}

This gives: 这给出:

new Object version Elapsed msec=13923
StackTrace version Elapsed msec=13459
Constant   version Elapsed msec=13

The two versions consume similar amounts of time but the hardcoded version is 1000 times faster. 这两个版本消耗的时间相似,但是硬编码版本的速度要快1000倍。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM