title: Java generics - use member method of unknown class
body: <p>So I have an Interface <code>MyInterface&lt;T&gt;</code> which has a method <code>String save(T obj)</code>
  The implementing class has this definition <code>Animal&lt;T&gt; implements MyInterface&lt;T&gt;</code>. My Main function looks like this:</p>
  
  <pre><code>MyInterface&lt;Cow&gt; animal = new Animal&lt;Cow&gt;();
  Cow cow = new Cow();
  cow.setName("Rose");
  animal.save(cow);
  </code></pre>
  
  <p>So far so good, <code>animal.save()</code> can only save Cows which is type-safe.</p>
  
  <p>Now the problem. In my Animal class I have the save method, but before I save I want to know that my Cow has a name. The Cow class has a <code>getName()</code> method.</p>
  
  <p>Save method:</p>
  
  <pre><code>@Override
  public void save(T obj)
  </code></pre>
  
  <p>What would be an apropriate way to go from <code>T obj</code> to a Cow-object so I can use the member method <code>getName()</code>?</p>
  
  <p>My idea is:</p>
  
  <pre><code>@Override
  public void save(T obj)
  {
          Object unknown = obj.getClass().newInstance();
          if (unknown instanceof Cow)
          {
              String name = ((Cow) unknown).getName();
          }
  }
  </code></pre>
  
  <p>Is this "ok" java? I guess I could use reflection and search for all methods related to the <code>unknown</code> object as well.. </p>
  
  <p><strong>Update</strong>
  As long as I define <code>MyInterface&lt;Cow&gt; animal = new Animal&lt;Cow&gt;();</code> Like this I'm safe, but the problem apperas when it looks like this:</p>
  
  <pre><code>MyInterface&lt;Object&gt; animal = new Animal&lt;Object&gt;();
  </code></pre>
  
  <p>Then there is no <code>getName()</code> method.... </p>