开发者

compiling code that uses Class.isAssignableFrom() with and without a generics aware compiler

I have some Java code that needs to compile with current generics aware compilers as well as with older or exotic compilers that don't know about generics (yet). I managed to get almost all the code compile fine and without warnings except for the rare occasions where Class.isAssignableFrom()开发者_JAVA技巧 is used.

This example compiles with either compiler but generics aware compilers give a warning like:

"Type safety: The method isAssignableFrom(Class) belongs to the raw type Class. References to generic type Class should be parameterized"

public static boolean isType( Class type, Class clazz )
{
    return type.isAssignableFrom( clazz );
}

This gets rid of the warning but of course doesn't compile without generics:

public static boolean isType( Class<?> type, Class clazz )
{
    return type.isAssignableFrom( clazz );
}

I managed to fix some cases by substituting this against Class.isInstance() and some others using MyClass.class.isAssignableFrom( clazz ) which compiles fine everywhere but a few cases are left where I really need Class.isAssignableFrom() to be invoked on a arbitrary class object. @SuppressWarnings isn't possible to use either since it's also only understood by compilers aware of Java 1.5 extensions and newer.

So any ideas how to fix this or do I just have to live with the warnings?


Live with that warning, or use conditional compiling (depends on the build tool you use)... Although I don't think it is a good practice trying to support two versions of Java which aren't compatible. And they may be worse things than just warnings on compiling.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜