Jas*_*n S 23 java generics compiler-errors javac
还有其他一些SO问题正在讨论使用Eclipse编译器编译OK的泛型而不是javac(即Java:Generics在Eclipse中处理差异,javac和Generics编译并在Eclipse中运行,但不在javac中编译) - 但这看起来很像就像一个略有不同的人.
我有一enum节课:
public class LogEvent {
public enum Type {
// ... values here ...
}
...
}
Run Code Online (Sandbox Code Playgroud)
我有另一个类,其方法可以接收来自Enum以下类型的任意对象:
@Override public <E extends Enum<E>> void postEvent(
Context context, E code, Object additionalData)
{
if (code instanceof LogEvent.Type)
{
LogEvent.Type scode = (LogEvent.Type)code;
...
Run Code Online (Sandbox Code Playgroud)
这在Eclipse中工作得很好,但是当我做一个干净的构建时ant,我得到一对错误,一个instanceof在线上,另一个在转换线上:
443: inconvertible types
[javac] found : E
[javac] required: mypackage.LogEvent.Type
[javac] if (code instanceof LogEvent.Type)
[javac] ^
445: inconvertible types
[javac] found : E
[javac] required: com.dekaresearch.tools.espdf.LogEvent.Type
[javac] LogEvent.Type scode = (LogEvent.Type)code;
[javac] ^
Run Code Online (Sandbox Code Playgroud)
为什么会发生这种情况,如何解决这个问题以便正确编译?
Jon*_*eet 32
我不知道为什么会这样,但解决方法很简单:
@Override public <E extends Enum<E>> void postEvent(
Context context, E code, Object additionalData)
{
Object tmp = code;
if (tmp instanceof LogEvent.Type)
{
LogEvent.Type scode = (LogEvent.Type)tmp;
...
Run Code Online (Sandbox Code Playgroud)
这很难看,但它有效......
也许是因为你宣称E是扩展Enum <E>的东西.我不能说我完全理解它,但看起来它将类型集限制为某些子集,由于某种原因不能包含LogEvent.Type.或许它只是编译器中的一个错误.如果有人能够更清楚地解释它,我会很高兴,但这是你可以做的:
public <E extends Enum<?>> void postEvent(E code)
{
if (code instanceof LogEvent.Type)
{
LogEvent.Type scode = (LogEvent.Type)code;
...
}
...
Run Code Online (Sandbox Code Playgroud)
这可以工作,它比仅仅转换为Object更优雅.