Note that there are some explanatory texts on larger screens.

plurals
  1. POJava Generics: Generic type defined as return type only
    text
    copied!<p>I'm looking at some GXT code for GWT and I ran across this use of Generics that I can't find another example of in the Java tutorials. The class name is <a href="http://extjs.com/deploy/gxtdocs/com/extjs/gxt/ui/client/data/BaseModelData.html" rel="noreferrer"><code>com.extjs.gxt.ui.client.data.BaseModelData</code></a> if you want to look at all of the code. Here are the important parts:</p> <pre><code>private RpcMap map; public &lt;X&gt; X get(String property) { if (allowNestedValues &amp;&amp; NestedModelUtil.isNestedProperty(property)) { return (X)NestedModelUtil.getNestedValue(this, property); } return map == null ? null : (X) map.get(property); } </code></pre> <p><code>X</code> is defined nowhere else in the class or anywhere in the hierarchy, and when I hit "go to declaration" in eclipse it just goes to the <code>&lt;X&gt;</code> in the public method signature.</p> <p>I've tried to call this method with the following two examples to see what happens:</p> <pre><code>public Date getExpiredate() { return get("expiredate"); } public String getSubject() { return get("subject"); } </code></pre> <p>They compile and show no errors or warnings. I would think at the very least I would have to do a cast to get this to work.</p> <p>Does this mean that Generics allow a magic return value that can be anything and will just blow up at runtime? This seems counter to what generics are supposed to do. Can anyone explain this to me and possibly give me a link to some documentation that explains this a little better? I've went through Sun's 23 page pdf on generics and every example of a return value is defined either at the class level or is in one of the parameters passed in.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload