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;
}
}
}