java 获取当前包名
可以使用Thread.currentThread().getStackTrace()方法获取当前线程的堆栈信息,然后从堆栈信息中解析出当前类的包名。
下面是一个示例代码:
public class Main {
public static void main(String[] args) {
String packageName = getPackageName();
System.out.println(packageName);
}
public static String getPackageName() {
String className = Thread.currentThread().getStackTrace()[2].getClassName();
int lastDotIndex = className.lastIndexOf(".");
if (lastDotIndex != -1) {
return className.substring(0, lastDotIndex);
} else {
return "";
}
}
}
输出结果为当前类所在的包名
原文地址: https://www.cveoy.top/t/topic/h0Mh 著作权归作者所有。请勿转载和采集!