Search code examples
javaandroidweak-references

Why we use get() method after Weak Reference Object Instances (Like Text View)?


Why we use get() method after WeakReference Text View Instance?

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 ");
}

why we can not set the text of textView straightly in weak reference without get() method?


Solution

  • Because as far as the compiler is concerned, the type WeakReference<TextView> is completely unrelated to TextView. WeakReference is a totally different class from TextView.

    Consider this code:

    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());
    

    You are basically asking

    Why can't I call foo.func() directly? Why do I have to call foo.get().func()?

    Because func is declared in Bar, not in Foo. And foo.get() returns an instance of Bar, which you can use to call func.

    setText is declared in TextView, not in WeakReference. WeakReference.get gives you an instance of TextView, which you can use to call setText.