java - 是否可以在构造函数中使用此类实例?

标签 java android constructor broadcastreceiver this

这只是让我感到困惑的事情。是否可以在构造函数中使用该类的当前实例?

我已经创建了一个 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");
        }
    }
}

最佳答案

是的,一点问题都没有。

在构造函数中,对象已创建,但仍未返回对其余 java 代码的引用。您可以放心地使用 this

无论如何,在某些属性可能会自动初始化的框架中(上下文相关注入(inject),CDI),不可能在构造函数中完全初始化类(因为这些属性仍然不可用并且可能需要)。这些框架依赖于您将方法标记为 @PostConstruct;设置所有属性后,将调用该方法(只是为了让您在找到它时知道它的含义)。

关于java - 是否可以在构造函数中使用此类实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12226277/

相关文章:

java - JSP: 新套接字 ("www", 80);工作多年后停止工作

android - 可以从工作线程调用 NotificationManager.notify() 吗?

android studio 构建 AVD 未知错误

c++ - 如何将 std::map 作为默认构造函数参数传递

java - 向现有的 java POJO 添加一个新的成员变量

java - com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException。 WHERE 子句

java - 如何将一些值加载到对象数组的实例中?

android - WrongViewCast 错误 : Unexpected implicit cast to TabLayout: layout tag was Linear Layout

php - php中有多少种构造函数

Java:获取鼠标的轮询率?