为什么我们在弱引用对象实例(如文本视图)之后使用 get() 方法?
Why we use get() method after Weak Reference Object Instances (Like Text View)?
为什么我们在WeakReference Text View实例之后使用get()方法?
private WeakReference<TextView> mTitleText;
private TextView mAuthorText;
FetchBook(TextView titleText, TextView authorText) {
this.mTitleText = new WeakReference<>(titleText);
this.mAuthorText = authorText;
//in weakPreference Text View
mTitleText.get().setText("hello");
//in standard text view
authorText.setText("by by ");
}
为什么没有get()
方法不能直接在弱引用中设置textView的文本?
因为对于编译器而言,类型WeakReference<TextView>
与TextView
完全无关。 WeakReference
与 TextView
完全不同 class。
考虑这段代码:
Foo<T> {
private T bar;
public T get() { return bar; }
public Foo(T bar) {
this.bar = bar;
}
}
class Bar {
public void func() {}
}
...
Foo<Bar> foo = new Foo(new Bar());
你基本上是在问
Why can't I call foo.func()
directly? Why do I have to call foo.get().func()
?
因为func
是在Bar
中声明的,而不是在Foo
中声明的。 foo.get()
returns Bar
的一个实例,你可以用它来调用 func
.
setText
在 TextView
中声明,而不是在 WeakReference
中声明。 WeakReference.get
给你一个 TextView
的实例,你可以用它来调用 setText
.
为什么我们在WeakReference Text View实例之后使用get()方法?
private WeakReference<TextView> mTitleText;
private TextView mAuthorText;
FetchBook(TextView titleText, TextView authorText) {
this.mTitleText = new WeakReference<>(titleText);
this.mAuthorText = authorText;
//in weakPreference Text View
mTitleText.get().setText("hello");
//in standard text view
authorText.setText("by by ");
}
为什么没有get()
方法不能直接在弱引用中设置textView的文本?
因为对于编译器而言,类型WeakReference<TextView>
与TextView
完全无关。 WeakReference
与 TextView
完全不同 class。
考虑这段代码:
Foo<T> {
private T bar;
public T get() { return bar; }
public Foo(T bar) {
this.bar = bar;
}
}
class Bar {
public void func() {}
}
...
Foo<Bar> foo = new Foo(new Bar());
你基本上是在问
Why can't I call
foo.func()
directly? Why do I have to callfoo.get().func()
?
因为func
是在Bar
中声明的,而不是在Foo
中声明的。 foo.get()
returns Bar
的一个实例,你可以用它来调用 func
.
setText
在 TextView
中声明,而不是在 WeakReference
中声明。 WeakReference.get
给你一个 TextView
的实例,你可以用它来调用 setText
.