java - How can I get the caller class object from a method in java?
问题描述
I know I can get the method and classname from StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
but that is not what I want.
I want the class object, so I can access his interface, annotations, etc...
It is possible?
Class<?> classObject = getCallerClass();
I see this question, but that is just for the classname.
How to get the caller class in Java
Edit: Now I'm passing the class this way:
someService.dummyMethod(foo1, foo2, new Object(){}.getClass());
someService(String foo1, int foo2, Class<?> c) {
// stuff here to get the methodname,
// the interface of the class and an annotation from the interface.
}
I call someService from a lot of different classes, If is not possible I will continue this way, but If there is a way to get the caller class at runtime I prefer that way.
解决方案
如果您使用的是 Java 9+,则可以使用java.lang.StackWalker
.
public void foo() {
Class<?> caller = StackWalker.getInstance(Option.RETAIN_CLASS_REFERENCE)
.getCallerClass();
}
但是,由于StackWalker
是线程安全的,因此创建一个实例并将其存储在某处可能是有益的(而不是每次调用该方法时都创建一个新实例)。
的Javadoc getCallerClass()
:
获取
Class
调用方法的调用者的对象getCallerClass
。此方法过滤反射帧、
MethodHandle
和隐藏帧,而不管已配置的SHOW_REFLECT_FRAMES
和SHOW_HIDDEN_FRAMES
选项。StackWalker
当调用者框架存在时,应该调用此方法。如果从堆栈的最底部帧调用它,
IllegalCallerException
将被抛出。
UnsupportedOperationException
如果StackWalker
未使用该RETAIN_CLASS_REFERENCE
选项配置此方法,则会引发此方法。
推荐阅读
- python - 如何读取和解析具有不同分隔符的日志文件
- ruby-on-rails - 在 Rails 路由器中访问请求上下文对象
- php - 如何在某些条件下使用 laravel 中的关系从多个表中获取数据?
- npm - NPM 没有将描述传递给脚本
- c# - 有什么方法可以验证 DI 的寿命吗?
- html - 在邮件中测试时如何使用网格布局修复电子邮件模板响应问题
- python - 选择带有 Selenium 变量的复选框
- mysql - 从mysql中的csv字符串生成字符串的索引/位置
- python - Python Discord 机器人嵌入
- html - 我可以在 Spring Boot 环境中使用 ckEditor 使用 Thymeleaf 吗?