最近在修改业务程序的时候,遇到了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
}
如有侵权 我会及时删除