0

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() 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?

x4u
  • 13,877
  • 6
  • 48
  • 58

1 Answers1

2

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.

khachik
  • 28,112
  • 9
  • 59
  • 94
  • Indeed, End Of Life has already gone by. Support for 1.4 ended in 2008, support for 5 ended in 2009. If you have to keep developing for those versions for reasons beyond your control, you have my sympathy. Otherwise, I recommend moving up to Java 6. – Pops Nov 16 '10 at 20:44
  • I do use current compilers wherever possible, but there are still several VMs i.e. targeting embedded platforms that either need a older file class format or want to compile from source code and don't know about generics. – x4u Nov 16 '10 at 20:55
  • 1
    I finally gave up on this approach. I'm now compiling everything in Java 5+ style and then postprocess the bytecode to make it compatible with 1.4 VMs again. This works pretty well and is far more convinient then to try to write code that compiles with and without generics. – x4u May 25 '11 at 21:47