java - "this"在例如 Intent(this, ClassName.class) 中使用时如何实际提供来自 Activity 的上下文

标签 java android android-intent

我知道如何实际使用intent,但是我不太明白

  1. 当您编写 this 并将其作为参数传递到 Activity 的方法中时,实际发生了什么。

我知道java中的保留关键字this指的是一个对象。我仔细检查了它对 javadocs 的真正作用

Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.

来自android documentation他们解释说 this 关键字引用了作为 Activity 类的父类(super class)的 Context 实例。

this is used because the Activity class is a subclass of Context

我不知道这究竟是如何工作的。我所知道的是,在 xml 中我定义了一个 onClick 监听器,它指定了一个方法名称,并且因为布局是从一个特定的类中膨胀的,所以我认为膨胀类的一个对象可能是在特定时间创建,this 引用此 Activity 对象。然后它会通过自动类型转换自动向下转换为父类(super class) Context 吗?

最佳答案

来自 Activity page

ava.lang.Object
   ↳    android.content.Context
       ↳    android.content.ContextWrapper
           ↳    android.view.ContextThemeWrapper
               ↳    android.app.Activity

我们还需要注意,Context 是一个抽象类,因此我们需要使用一些实现,因为在java 中不可能创建抽象类的实例。在这 Context page您可以看到所有“已知间接子类”:不仅 Activity 可以用作上下文

所以 Activity 扩展了 Context => Wiki Inheritance

What really happens when you write this and pass it as a parameter in a method from an Activity.

Passing subclass or superclass object to method (expecting a superclass object)

关于java - "this"在例如 Intent(this, ClassName.class) 中使用时如何实际提供来自 Activity 的上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30705422/

相关文章:

android - 可搜索 Activity 被调用两次

java - Java 相当于 C 的 fflush? [读取值时出现问题]

android - 为什么 TTakePhotoFromCameraAction.OnDidFinishTaking 事件在 Android 10 上不起作用?

java - 为什么 Java 中的 addLast() 替换了我的链表?

java - 带有滑动选项卡的搜索界面 android

android - 为 Zip 文件选择 Intent

java - Dropbox 图标未出现在共享托盘中

android - 浏览器中的 Intent ,是否可以在 Android 网络浏览器中从 Javascript 触发 Intent ?

java - Spring没有从systemd服务中看到环境变量

java - 如何在JSP中显示操作系统信息?