使用private static修饰方法有什么好处?

最近在修改业务程序的时候,遇到了private static修饰的一个方法,在该方法中调用另外一个私有方法时报错。

Non-static method 'sendAlarmMQ(java.lang.String, java.lang.String, java.lang.String)' cannot be referenced from a static context

 

 为何使用private static修饰方法总结下来就是:

  • Make it clear to the reader that they will not modify the state of the object.
  • The JIT compiler will anyways inline and optimize it.(编译器会更优先考虑将这些方法内联。)

 

根据这位前辈的说法就是仅仅为了清晰的知道该方法不可被对象改变,那至少该方法内部是不会涉及调用其他方法,只是单纯的做自己该做的。因此对于这次业务修改需要将static 修饰的方法内调用另外一个私有方法,因此就不能将该方法声明为static。

第二位前辈的意思大致是这样做好像会性能会提高,因为静态的函数无需检测this指针是否为空,他还很敬业的给了一个sample并且从指令代码的层次做了阐述。

class TestBytecodeSize {
    private void doSomething(int arg) { }
    private static void doSomethingStatic(int arg) { }
    public static void main(String[] args) {
        // do it twice both ways
        doSomethingStatic(0);
        doSomethingStatic(0);
        TestBytecodeSize t = new TestBytecodeSize();
        t.doSomething(0);
        t.doSomething(0);
    }
}

 

C:\Users\wx\Desktop\layout导入>javap -c TestBytecodeSize
Compiled from "TestBytecodeSize.java"
class TestBytecodeSize {
  TestBytecodeSize();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  public static void main(java.lang.String[]);
    Code:
       0: iconst_0
       1: invokestatic  #2                  // Method doSomethingStatic:(I)V
       4: iconst_0
       5: invokestatic  #2                  // Method doSomethingStatic:(I)V
       8: new           #3                  // class TestBytecodeSize
      11: dup
      12: invokespecial #4                  // Method "<init>":()V
      15: astore_1
      16: aload_1
      17: iconst_0
      18: invokespecial #5                  // Method doSomething:(I)V
      21: aload_1
      22: iconst_0
      23: invokespecial #5                  // Method doSomething:(I)V
      26: return
}

原文地址 :https://stackoverflow.com/questions/538870/should-private-helper-methods-be-static-if-they-can-be-static

如有侵权 我会及时删除

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值