Java中静态方法不依赖于具体的实例存在,所有不能直接使用this指针,需要别的方式间接的获取到类名。
方法
- 方法1:通过SecurityManager的保护方法getClassContext()
private static String test1() {
return new SecurityManager() {
public String getClassName() {
return getClassContext()[1].getName();
}
}.getClassName();
}
- 方法2:通过Throwable的方法getStackTrace()
private static String test2() {
return new Throwable().getStackTrace()[1].getClassName();
}
- 方法3:通过Thread.currentThread的方法getStackTrace()
private static String test3() {
return Thread.currentThread().getStackTrace()[1].getClassName();
}
- 方法4:通过分析匿名类名称()
private static String test4() {
return new Object() {
public String getClassName() {
String clazzName = this.getClass().getName();
return clazzName.substring(0, clazzName.lastIndexOf('$'));
}
}.getClassName();
}
性能
分别调用100w次测试性能
public static void main(String[] args) {
long start, end;
int total = 1000000;
String className = null;
start = System.currentTimeMillis();
for (int i = 0; i < total; i++) {
className = Main.test1();
}
end = System.currentTimeMillis();
System.out.println("test1: " + className + "time: " + (end - start) + " ms");
start = System.currentTimeMillis();
for (int i = 0; i < total; i++) {
Main.test2();
}
end = System.currentTimeMillis();
System.out.println("test2: " + className + "time: " + (end - start) + " ms");
start = System.currentTimeMillis();
for (int i = 0; i < total; i++) {
Main.test3();
}
end = System.currentTimeMillis();
System.out.println("test3: " + className + "time: " + (end - start) + " ms");
start = System.currentTimeMillis();
for (int i = 0; i < total; i++) {
Main.test4();
}
end = System.currentTimeMillis();
System.out.println("test4: " + className + "time: " + (end - start) + " ms");
}
测试结果: 直接分析匿名内部类名字性能最高
test1: com.rainlf.mult.Maintime: 463 ms
test2: com.rainlf.mult.Maintime: 1840 ms
test3: com.rainlf.mult.Maintime: 2193 ms
test4: com.rainlf.mult.Maintime: 21 ms