Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If I understood you correctly, you want to know the class (<em>type</em>) of an instance (<em>object</em>) in runtime (<em>existing</em>), which has nothing to do with generics though, as Petr explained.</p> <pre><code>public class Types { public static void main(String[] args) { String s = ""; Runtime r = Runtime.getRuntime(); Types t = new Types(); List&lt;Class&gt; types = new LinkedList&lt;Class&gt;(); types.add(Integer.class); types.add(t.getClass()); types.add(r.getClass()); types.add(s.getClass()); for (Class type :types) { System.out.println(type.getSimpleName()); } } } </code></pre> <p>which outputs:</p> <pre><code>Integer Types Runtime String </code></pre> <p>However, such approach is rarely needed, so rethink is there a simpler solution to your problem. If you still want to tackle it like this:</p> <ul> <li><a href="https://stackoverflow.com/questions/37628/what-is-reflection-and-why-is-it-useful">What is reflection, and why is it useful?</a></li> <li><a href="http://docs.oracle.com/javase/tutorial/reflect/index.html" rel="nofollow noreferrer">official tutorial</a></li> </ul> <p>EDIT:</p> <p>The other interpretation of your question leads to a dynamic generic list as answer:</p> <pre><code>public static &lt;T&gt; List&lt;T&gt; createListOfType() { return new ArrayList&lt;T&gt;(); } public static void main(String[] args) { List&lt;String&gt; a = createListOfType(); List&lt;Integer&gt; b = createListOfType(); a.add(""); b.add(2); a.add(2); // remove this line to compile b.add(""); // remove this line to compile } </code></pre>
 

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