Java的方法调用方检测
作者:互联网
0. 概述
本文使用Java异常中的堆栈信息来检测调用方的类是否为指定类,效果如下:
public class Main {
public static void main(String[] args) {
System.out.println(isCalledFrom(File.class)); // => print false
System.out.println(isCalledFrom(Main.class)); // => print true
test(); // => print true
}
static void test(){
System.out.println(isCalledDirectlyFrom(Main.class));
}
}
1. isCalledFrom
isCalledFrom判断是否直接或间接从某个类调用进来,定义如下:
public static boolean isCalledFrom(Class<?> mClass) {
try {
throw new RuntimeException();
} catch (Exception e) {
StackTraceElement[] stackTrace = e.getStackTrace();
for (int i = 0; stackTrace != null && i < stackTrace.length; i++) {
if (Objects.equals(mClass.getName(), stackTrace[i].getClassName())) {
return true;
}
}
return false;
}
}
2. isCalledDirectlyFrom
isCalledDirectlyFrom判断是否直接从某个类调用进来,定义如下:
public static boolean isCalledDirectlyFrom(Class<?> mClass) {
try {
throw new RuntimeException();
} catch (Exception e) {
StackTraceElement[] stackTrace = e.getStackTrace();
if (stackTrace != null && stackTrace.length > 2) {
return Objects.equals(stackTrace[2].getClassName(), mClass.getName());
} else {
return false;
}
}
}
乐征skyline
发布了16 篇原创文章 · 获赞 11 · 访问量 1万+
私信
关注
标签:stackTrace,调用,Java,检测,static,isCalledDirectlyFrom,isCalledFrom,return,public 来源: https://blog.csdn.net/zssrxt/article/details/104082544