[英]Is it possible to use this class instance in the constructor?
只是让我感到困惑。 是否可以在构造函数中使用该类的当前实例?
我创建了一个BroadcastReceiver,将其自身注册到BroadcastReceiver的构造函数中的上下文中。 此外,它将再次注销。 这是好风格吗?
这是我的示例:
public class MyBroadcastReceiver extends BroadcastReceiver {
protected Context context;
protected MyOnBroadcastReceivedListener listener;
protected int receiverId;
protected String receiverTag;
public MyBroadcastReceiver(int receiverId, Context context, MyOnBroadcastReceivedListener listener, String receiverTag) {
super();
this.context = context;
this.listener = listener;
this.receiverId = receiverId;
this.receiverTag = receiverTag;
IntentFilter intentFilter = new IntentFilter(receiverTag);
context.registerReceiver(this, intentFilter); // <--- Look at the use of this here
}
public void detach() {
if (context != null) {
context.unregisterReceiver(this); // <--- Look at the use of this
}
}
@Override
public void onReceive(Context context, Intent intent) {
// ...
if (listener != null) {
listener.onBroadcastReceived(receiverId, "Bla", "Blub");
}
}
}
如果您在构造函数代码中提到使用this
函数,则是的-它是完全有效的,否则构造函数将无法真正在自己的实例中进行大量构造。 但是,我建议遵循常规做法,为类成员添加前缀(最常用的前缀为'm'),这有助于避免有时难以调试的问题。 所以代替:
protected Context context;
protected MyOnBroadcastReceivedListener listener;
你将会拥有:
protected Context mContext;
protected MyOnBroadcastReceivedListener mListener;
是的,一点也不麻烦。
在构造函数内部,已创建对象,但仍未返回对其余Java代码的引用。 您可以毫无后顾之忧地使用this
。
无论如何,在某些框架中某些属性可以自动初始化的情况下(上下文相关注入,CDI),不可能在构造函数中完全初始化该类(因为此类属性仍然不可用,可能仍需要)。 这些框架依赖于您将方法标记为@PostConstruct
; 设置完所有属性后,将调用该方法(只是为了让您知道找到该方法的含义)。
您可以执行此操作,但是样式不是很好。 从类构造函数内部传递this
很危险,因为当前仍在构造的对象可能无法完全初始化。
例如,您可能有一天可能会在MyBroadcastReceiver
添加一个新的int字段,但会忽略您具有以下语句的context.registerReceiver(this, intentFilter);
并在构造函数的末尾添加新字段的初始化:
public MyBroadcastReceiver(int receiverId, Context context, MyOnBroadcastReceivedListener listener, String receiverTag) {
super();
this.context = context;
this.listener = listener;
this.receiverId = receiverId;
this.receiverTag = receiverTag;
IntentFilter intentFilter = new IntentFilter(receiverTag);
context.registerReceiver(this, intentFilter); // <--- Look at the use of this here
this.newField = 1;
}
现在,你可能会认为在Context.registerReceiver
法newField
为1,因为它在被初始化的MyBroadcastReceiver
构造。 但是您将获得值0。
另请参见以下SO问题以获取更多信息和可能出现的更多潜在问题: 在Java构造函数中传递“ this”
是的,它有效。 我尝试了一个简单的测试用例。 而且有效。 :
public class Test {
private int variable;
private Test2 test2;
public Test(int variable, Test2 test2) {
this.variable = variable;
this.test2 = test2;
test2.printTest(this);
}
public int getVariable() {
return variable;
}
public static void main(String[] args) {
Test test = new Test(111111,new Test2());
}
}
class Test2{
Test2() {
}
public void printTest(Test test){
System.out.println(test.getVariable());
}
}
它就像一个魅力
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.