Java获取当前类名和方法名

川长思鸟来 2024-03-26 10:31 215阅读 0赞

获取class名:

非static method中使用:

  1. this.getClass().getName();// 这是完整的类路径名
  2. this.getClass().getSimpleName();// 仅仅是类名

static method中使用:

  1. Thread.currentThread().getStackTrace()[1].getClassName();

获取方法名:

  1. Thread.currentThread().getStackTrace()[1].getMethodName();

获取行号:

  1. Thread.currentThread().getStackTrace()[1].getLineNumber();

Log 代码:

  1. System.out.println("Class: "+this.getClass().getName()+" method: "+Thread.currentThread().getStackTrace()[1].getMethodName() +" line:"+Thread.currentThread().getStackTrace()[1].getLineNumber());

获取文件名(带后缀):

  1. Thread.currentThread().getStackTrace()[1].getFileName();

完整示例:

  1. package com.hello.demo;
  2. public class TestA {
  3. public void hello() {
  4. System.out.println("hello world");
  5. String className = this.getClass().getName();
  6. String simpleClassName = this.getClass().getSimpleName();
  7. String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
  8. // hello world
  9. //className: com.hello.demo.TestA, simpleClassName: TestA, methodName: hello
  10. System.out.println("className: " + className + ", simpleClassName: " + simpleClassName + ", methodName: " + methodName);
  11. }
  12. public static void main(String[] args) {
  13. new TestA().hello();
  14. }
  15. }

https://blog.csdn.net/cnds123321/article/details/122812305

发表评论

表情:
评论列表 (有 0 条评论,215人围观)

还没有评论,来说两句吧...

相关阅读