Is it an eclipse or maven-compiler-plugin bug, the generics Class cast issue?
I have a code like this:
protected <T> T doSomething(String someParam, Class<T> clazz) {
...
}
which I use in a TestCase class:
Class clazz = MyClass.class;
MyClass MyClass = someObject.doSomething(someString, clazz);
This code gives a warning in eclipse:
Class is a raw type. References to generic type Class should be parameterized
and
Multiple markers at this line
- Type safety: Unchecked invocation doSomething(String, Class) of the generic method doSomething(String, Class) of type MyClass - Type safety: The expression of type Class needs unchecked conversion to conform to Class
When I run this code (test) in eclipse - everything works perfectly. When I do it through "mvn clean install" through command prompt, I get:
C:\pathToProject\src\test\java\packagesPath\MyTestCase.java:[xx,xxx] incompatible types found :
java.lang.Object required: com.somePackagePath.MyClass
But when providing:
Class<MyClass> clazz = MyClass.class;
MyClass MyClass = someObject.doSomething(someString, clazz);
I don't get any errors nor warnings. .
I understand that java compiler erases type info, so: Shouldn't eclipse provide a compiler error instead of warning, or is it the maven-plugin-compiler that creates the problem? The maven plugin is: <plugin>
<groupId>org.apache.maven.p开发者_运维问答lugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
<showDeprecation>false</showDeprecation>
<debug>true</debug>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
Kind Regards,
DespotThis is a known bug in Eclipse: 333011: [compiler][1.5] Eclipse compiles codes which javac rejects: incompatible types . Feel free to vote for the bug and add your use case to it.
There are situations when javac
and Eclipse disagree, and you should report them as bugs. It is preferred to have a standalone test case of as few Java files as possible which can be copy/pasted in Eclipse and compiled using javac
from the command line without any dependencies.
Which compiler are you using? In this case http://code.google.com/p/jclouds/issues/detail?id=461 the openjdk seems to reveal the incompatible types while the sun jdk ignores it and compiles.
A workaround is using eclipse compiler in maven as described at Using Eclipse Java Compiler (ecj) in maven builds
精彩评论