Same source code, Eclipse build success but Maven

2020-06-16 05:34发布

问题:

Keep getting this error when compiling using Maven:

type parameters of <X>X cannot be determined; no unique maximal instance exists for type variable X with upper bounds int,java.lang.Object

Generics type interference cannot be applied to primitive types. But I thought since Java5, boxing/unboxing mechanism works seamlessly between primitive types and wrapper classes.

In any case, the strange thing is Eclipse doesn't report any errors and happily compiles. I'm using JDK1.6.0_12. What could possibly be the problem here?

回答1:

This issue can occur when your code is generic and it calls another method that has a generic return type. Sometimes the compiler gets confused trying to figure out how to resolve the method call / return type.

It can be resolved by adding an explicit cast to your code.

// Old code:
public T getValue() {
    return otherMethod();  // otherMethod has the signature: <RT> RT otherMethod() { ... }
}

// New code:
@SuppressWarnings("unchecked")
public T getValue() {
    return (T) otherMethod();   // the cast tells the compiler what to do.
}


回答2:

A few things to look at:

  1. Both Eclipse and Maven are using the same java/bin installation
  2. Eclipse and Maven are using the same libraries, one might have something the other does not.


回答3:

I met the same error,use ant. Because when compile by ant or maven,javac use JDK to compile.But in eclipse,it has JDT,that can compile success.

I add below script in my build.xml file: <property name="build.compiler" value="org.eclipse.jdt.core.JDTCompilerAdapter" /> Then,ant can build success.

I am not familiar with Maven. Maybe,it can set the compiler?

In my source code,there are many code like this: public <X> X find(String hql, Object... values) { return (X) HibernateUtils.createQuery(getSession(), hql, values).uniqueResult(); }

Maybe your code too.

But,use JDT,the success is't the final success,in ant. build.xml can build success only in eclipse. when I run ant from windows command,fail. Throw another error: Class not found: org.eclipse.jdt.core.JDTCompilerAdapter

PS, I have copy jar files about JDT in eclipse plugin to ant_home/lib directory.

Wish a little help to you.And our problem can solve.



回答4:

It definitely has to do something with the JDK versions maven and eclipse are using. Also make sure your Compiler compliance level in eclipse points to the right JDK version.