Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The reason why T.class can't be accessed is because T is erased at compile time, so it doesn't exist at runtime to get a class.</p> <p>The typical hack around this is to make a factory method:</p> <pre><code> public static &lt;T extends Serializable&gt; BaseDAOImpl&lt;T&gt; createBaseDAO(Class&lt;T&gt; klass) { return new BaseDAOImpl&lt;T&gt;(klass); } </code></pre> <p>And then in the constructor store the klass variable as a field and reference it when you need it.</p> <p>You could use your interface (personally I would just go with a protected abstract method) if you want to keep a no-arg constructor.</p> <pre><code> protected abstract Class&lt;T&gt; getGenericClass(); </code></pre> <p>EDIT: In the case of the generic abstract superclass, there are a couple of options. One is have the constructor and then have the subclasses just have to call it (by not having a no-arg constructor). Something like this:</p> <pre><code> protected BaseDAOImpl(Class&lt;T&gt; klass) { //store the parameter in a field. } </code></pre> <p>Then the static method isn't relevant, as you have to create the subclass. The static factory method is more used when based on the class you can return the right implementation (so you have a factory, not just a strategy).</p> <p>For the sake of completeness, I should point out that if the subclasses declare the generic when they extend the abstract class like this:</p> <pre><code> public IntegerImpl extends BaseDAOImpl&lt;Integer&gt; {} </code></pre> <p>then the generic type is preserved in the class. There is a really ugly hack to get at this using the class. I experimented with this, and it worked:</p> <pre><code> (Class&lt;?&gt;) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0] </code></pre> <p>But it makes huge assumptions about the inheritance hierarchy, and should not be used in anything serious if it can at all be avoided, but I'm including it for the sake of a complete picture of what is going on.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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