title: Determine required object type from uninitialized object
body: <p>I would like my code to help determine what object type is required automatically.</p>
  
  <p><strong>Background:</strong></p>
  
  <p>The code to attach a widget is often as follows:</p>
  
  <pre><code>TextView textView = (TextView) findViewById(R.id.textView);
  </code></pre>
  
  <p>I want to then check that textView has been found correctly in order to avoid bugs. To do this, I'm using a custom (AttachWidgetException) exception:</p>
  
  <pre><code>if(textView == null) throw new AttachWidgetException(name);
  </code></pre>
  
  <p><strong>Idea:</strong></p>
  
  <p>Rather than having to repeat these two lines for every widget in my code (DRY), I decided to make a function to simplify it. I incorrectly assumed I could do this:</p>
  
  <pre><code>public View attachWidget(View view, int resID, String name) throws AttachWidgetException {
      view = (view.getClass) findViewById(resID);
  
      if(view == null) throw new AttachWidgetException(name);
      return view;
  }
  </code></pre>
  
  <p>Called from within a <em>Try</em> block by:</p>
  
  <pre><code> TextView textView = attachWidget(textView, R.id.textView, "textView");
  </code></pre>
  
  <p><strong>Problem:</strong></p>
  
  <p>But, this doesn't work for two reasons. The caller's object is expecting a TextView not a View. I think the other reason is <em>view</em> is yet to be instantiated and therefore  is reported as:</p>
  
  <pre><code>java.lang.Class &lt;capture&lt;? extends android.view.View&gt;
  </code></pre>
  
  <p>… which is not an extension of View. To fix this, I need to change the line in attachWidget to:</p>
  
  <pre><code>view = findViewById(resID);
  </code></pre>
  
  <p>...and the calling line to:</p>
  
  <pre><code>TextView textView = (TextView) attachWidget(textView, R.id.textView, "textView");
  </code></pre>
  
  <p>… which makes the View input parameter useless. We can remove that at this point.</p>
  
  <p><strong>Question:</strong></p>
  
  <p>This really isn't too bad, but is there a way to do this so I don't need to manually add the cast? Can <em>attachWidget</em> automatically determine that it needs to return a TextView? I'm pretty sure I'm heading in the wrong direction of any possible solutions. Would generics help me in any way here?</p>
  
  <p>Please forgive me if I am using incorrect terminology in my description. I would appreciate any code / terminology / methodology corrections. </p>