我知道如何实际使用intent
,但是我不太明白
- 当您编写
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
吗?
最佳答案
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/