Quantcast
Channel: User Jonathan - Stack Overflow
Viewing all articles
Browse latest Browse all 40

Answer by Jonathan for Create instance of generic type in Java?

$
0
0

Here's an implementation of createContents that uses TypeTools (which I authored) to resolve the raw class represented by E:

E createContents() throws Exception {  return TypeTools.resolveRawArgument(SomeContainer.class, getClass()).newInstance();}

This approach only works if SomeContainer is subclassed so the actual value of E is captured in a type definition:

class SomeStringContainer extends SomeContainer<String>

Otherwise the value of E is erased at runtime and is not recoverable.


Viewing all articles
Browse latest Browse all 40

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>