0

Assume there is a generic Query class which performs a db query and return the mapped object.

Public class Query
{
    public <T> T getObject(Class<T> type){
    {
          // get the data and build object using reflection

          return T;
    }
}

Now somewhere in the code, consuming "Query" like below:

Query q = new Query();
T result = q.<Person>getObject(person.getClass());
 

This compiles and runs fine in eclipse environment. But fails in ANT/Gradle build. During ANT/Gradle compile, java compiler is simply ignoring generic type <T> passed while invoking the method. And baseline the runtime type as the one passed in the argument which "Class" not "Class<T>". And throws incompatible types error:

[javac] Query.java:18: error: incompatible types

[javac] T result = q. getObject(person.gerClass());

[javac] ^

[javac] required: T

[javac] found: Object

[javac] where T is a type-variable:

[javac] T extends Object declared in class Query

However if I cast either parameter or result, it compiles in ANT/Gradle without any issues. Say like below.

T result = q.<Person>getObject((Class<T>)person.getClass());

or

T result = (T) q.<Person>getObject(person.getClass());

I am curious to know why the code that compiles fine in eclipse environment fails in ANT/Gradle build? Is there any environment or compile time argument that enforce generic type check?

Community
  • 1
  • 1
vinodpthmn
  • 1,062
  • 14
  • 28
  • Eclipse has it's own compiler https://stackoverflow.com/questions/3061654/what-is-the-difference-between-javac-and-the-eclipse-compiler – lance-java Jan 23 '18 at 13:47
  • 1
    Eclipse has its own compiler that differs from `javac` (e. g. see https://stackoverflow.com/q/45798233/6505250). Also, different compiler versions can be different. To get the same result, you have to use the same compiler. To use the Eclipse compiler in Gradle, see https://stackoverflow.com/q/46196120/6505250 – howlger Jan 23 '18 at 16:44

0 Answers0