通话this.method()和method()(包括性能差异)之间有什么区别吗?
Pet*_*rey 59
唯一重要的是你是否正在使用OuterClass.this.method()eg
class OuterClass {
void method() { }
class InnerClass {
void method() {
OuterClass.this.method(); // not the same as method().
}
}
}
Run Code Online (Sandbox Code Playgroud)
Tom*_*icz 28
这些结构之间完全没有区别,生成的字节码将完全相同,因此不会影响性能.this如果没有明确定义,则在编译期间解析.
使用显式的唯一原因this是可读性 - 有些人发现它更容易阅读,因为这this表明这是当前对象的实例方法.
另请注意,如果method()是静态的,使用this是不鼓励和误导.
private static void method() {
}
private void foo() {
this.method(); //generates warning in my IDE for a reason
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,它也不会影响性能.
Atr*_*eys 18
通过调用javap -c ClassName命令行可以看出没有区别.例如:
public class This {
private void method() {
}
public void noThis() {
method();
}
public void useThis() {
this.method();
}
}
Run Code Online (Sandbox Code Playgroud)
产生以下反汇编输出:
Compiled from "This.java"
public class This extends java.lang.Object{
public This();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public void noThis();
Code:
0: aload_0
1: invokespecial #2; //Method method:()V
4: return
public void useThis();
Code:
0: aload_0
1: invokespecial #2; //Method method:()V
4: return
}
Run Code Online (Sandbox Code Playgroud)
对于方法没有区别,但它可以对字段产生影响.考虑以下代码:
private String someObject = "some value";
public String someMethod(String someObject) {
//this.someObject refers to the field while
//someObject refers to the parameter
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
33072 次 |
| 最近记录: |