[size=large]今天中午趁休息时间玩了玩android发现这样的一段代码[/size]
[size=large]从以上代码中可见[color=red]MyActivity.this[/color]的用法,平时一直搞J2EE也没注意过这种写法,来了兴趣,网上找了找,没找到有用的信息(和目前搜索引擎和自己描述有关),自己尝试豁然晓得了,写个例子总结下[/size]
上班时间时间紧举不出什么好的例子来
[size=large]在People.eat()里面如果不用People.this那么得到this指向的是匿名的Water,这样就可以区分两个不通的this,和两个实例下的同名方法了[/size]
package com.lidongbo;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MyActivity extends BaseActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button=(Button)findViewById(R.id.Button01);
button.setOnClickListener(backOnClickListener);
}
private Button.OnClickListener backOnClickListener=new Button.OnClickListener() {
public void onClick(View v) {
MyActivity.this.setResult(RESULT_OK, intent);
MyActivity.this.finish();
}
};
}
[size=large]从以上代码中可见[color=red]MyActivity.this[/color]的用法,平时一直搞J2EE也没注意过这种写法,来了兴趣,网上找了找,没找到有用的信息(和目前搜索引擎和自己描述有关),自己尝试豁然晓得了,写个例子总结下[/size]
上班时间时间紧举不出什么好的例子来
package lidongbo.test;
public class Water {
public void wash(){
}
public void run(){
System.out.println("Water run");
}
public static void byDrink (People man){
//...
}
}
package lidongbo.test;
public class People {
public void talk(){
System.out.println("talk");
}
public void run(){
System.out.println("People run");
}
public void drink(){
People.this.talk();
new Water(){
void play(){
talk();//默认得到全部的(包括Water和People的)
this.wash();//直接this.只得到Water
People.this.talk();
byDrink(People.this);//默认得到全部但是需要传递People引用,就要使用People.this
run();
this.run();
People.this.run();//如果想调用People的run方法,就要用People.this
}
}.play();
}
public static void main(String[] args) {
People man=new People();
man.drink();
}
}
[size=large]在People.eat()里面如果不用People.this那么得到this指向的是匿名的Water,这样就可以区分两个不通的this,和两个实例下的同名方法了[/size]