当前位置: 首页 > news >正文

Java获取当前类名的两种方法

适用于非静态方法:this.getClass().getName()

适用于静态方法:Thread.currentThread().getStackTrace()[1].getClassName()

获取类名:

1、在类的实例中可使用this.getClass().getName();但在static method中不能使用该方法;

2、在static method中使用方法:Thread.currentThread().getStackTrace()[1].getClassName();

获取方法名:Thread.currentThread().getStackTrace()[1].getMethodName();

获取代码行号:Thread.currentThread().getStackTrace()[1].getLineNumber();

Log 代码:

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

Below I present you two different ways to get the current Class:

  • Using Thread
  • Using getClass()

getClass() method present in every Java object. Like here:

String clazz = this.getClass().getName();

static method. It won't work. Even the keyword this is meaningless in a static method.

Also, the class returned by the above method may actually be a subclass of the class in which the method is defined. This is because subclasses inherit the methods of their parents; and getClass() returns the actual runtime type of the object. To get the actual class in which a method is defined, use the method below also.

static method you can instead use the following:

String clazz = Thread.currentThread().getStackTrace()[1].getClassName();

Which uses the static methodgetStackTrace() to get the whole stacktrace. This method returns an array, where the first element (index 0) is the getStackTrace() you called and the second element (index 1) is the method your code is in.

 

String method = Thread.currentThread().getStackTrace()[1].getMethodName();
http://www.lryc.cn/news/151095.html

相关文章:

  • windows系统开机自启打开指定网页
  • Java-HashMap中put()方法是如何实现的,内含详细流程图
  • kaggle赛后总结
  • 基于Vue前端框架构建BI应用程序
  • 【文心一言】学习笔记
  • Xilinx UltraScale架构之可配置逻辑块CLB
  • springboot web开发整合Freemarker 模板引擎
  • Python 连接 SQL 数据库 -pyodbc
  • Vue框架--Vue中的数据代理
  • 每日一题(链表中倒数第k个节点)
  • python如何求两list的公共区域
  • SpringMVC中文乱码(request或response)前后端处理
  • Redis面试题大全含答案
  • stable diffusion实践操作-提示词-整体环境
  • Spring Aop--通知注解
  • 说说CDN和负载均衡具体是怎么实现的
  • Leetcode107. 二叉树的层序遍历 II
  • 【广州华锐互动】VR党建多媒体互动展厅:随时随地开展党史教育
  • libdrm全解析三十九 —— 源码全解析(36)
  • 【Interaction交互模块】AngularJointDrive角度关节驱动
  • 菜鸟教程《Python 3 教程》笔记 EX 01:命令行参数
  • NLP(六十六)使用HuggingFace中的Trainer进行BERT模型微调
  • Rabbitmq消息积压问题如何解决以及如何进行限流
  • Lambda方法引用
  • TCP协议报文
  • C# 如何将使用的Dll嵌入到.exe应用程序中?
  • 【LeetCode】剑指 Offer Ⅱ 第5章:哈希表(6道题) -- Java Version
  • x86 汇编手册快速入门
  • WPF C# Binding绑定不上的解决情况
  • 【UE 材质】实现方形渐变、中心渐变材质