javapolymorphismerasure

Java 1.6 -> 1.8, same erasure compile error


I'm porting my Java app from 1.6 to 1.8 and the compiler is unhappy with the methods getAbstractTransactionCriteria() in the following code:

public abstract class AbstractTransaction ...
public class TemplateTransaction extends AbstractTransaction ...
public class Transaction extends AbstractTransaction ...

abstract class AbstractTransactionCriteria {...}
class TransactionCriteria extends AbstractTransactionCriteria {...}
class TemplateCriteria extends AbstractTransactionCriteria {...}

TransactionCriteria getAbstractTransactionCriteria(Class<Transaction> c) {...}
TemplateCriteria    getAbstractTransactionCriteria(Class<TemplateTransaction> c) {...}

The compiler tells me the two methods have the same erasure, which I can accept because I've seen elsewhere that the things inside the angle brackets get replaced by Object by the compiler.

The arguments c are only there to achieve the polymorphism (they're not used in the method bodies) and this used to work perfectly in Java 1.6.

What should I do to achieve the same result in 1.8?


Solution

  • If you are at liberty to change the function prototypes, and the arguments are not used except to determine the return type, then would the following work for you?

    TransactionCriteria getAbstractTransactionCriteria(Transaction c) {...}
    TemplateCriteria    getAbstractTransactionCriteria(TemplateTransaction c) {...}
    

    Alternatively, you could use different function names and have them take no arguments. For example

    TransactionCriteria getAbstractTransactionCriteria() {...}
    TemplateCriteria    getAbstractTemplateCriteria() {...}