zoukankan      html  css  js  c++  java
  • paip.java c++得到当前类,方法名称以及行号

    paip.java c++得到当前类,方法名称以及行号

    作者Attilax 艾龙,  EMAIL:1466519819@qq.com
    来源:attilax的专栏
    地址:http://blog.csdn.net/attila

    得到当前类名称(带package 路径)
                //m.util.tAnno
            System.out.println(    Thread.currentThread().getStackTrace()[1].getClassName());

    6.2    得到当前方法的名字
        String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
            System.out.println(methodName);
            
    6.3    取当前源文件中文件名和行号

    在C/C++的程序,编译器提供了两个宏来支持取得源文件中的行号和文件名,这两个宏是__FILE__,__LINE__
    你可以如下的方法打印行号和文件名
     
    6    #include <stdio.h>
    int main()
    {
     fprintf(stdout,"[%s:%d] Hello World!",__FILE__,__LINE__);
     return 0;
    }

    但是在JAVA下没有这两个宏,那么我们如何来取得文件名和行号,翻阅JDK,我们找到StackTraceElement这个类。这个类可以从Throwable取得,另外也可以从Thread类取得,通过这些我写如下的一个打印行号的测试程序:
     
    12    public class LineNo {
     public static int getLineNumber() {
     return Thread.currentThread().getStackTrace()[2].getLineNumber();
     }  
     
     public static String getFileName() {
     return Thread.currentThread().getStackTrace()[2].getFileName();
     }
     public static void main(String args[]) {
     System.out.println("["+getFileName()+":"+ getLineNumber()+"]"+"Hello World!");
     }
    }
    最后中括号里面一定是1,如果换成0,那就打印的是调用该方法的主方法所在的行数,如果换成2,那就是方法调用结束后,返回到哪一行。例如
    参考
    StackTraceElement类使用说明_百度文库

  • 相关阅读:
    sudo: no tty present and no askpass program specified 解决方法
    中间件kingshard入门(一):基本安装
    mysql主从配置
    haproxy+keepalive双主高可用实现负载均衡
    lvs负载均衡配置
    docker可视化集中管理工具shipyard安装部署
    安装nodejs
    redis数据导入与导出以及配置使用
    搭建ss5环境
    thinkphp5+python.apscheduler实现计划任务
  • 原文地址:https://www.cnblogs.com/attilax/p/5964087.html
Copyright © 2011-2022 走看看