java static getclass,Java 静态方法获取当前类

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值