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?