I'm working with an older Java application that was written for Java 1.4, before Generics were available. Since then, we have completed our upgrade to Java 6.
We are now looking into making a change to support Generics in our collections for the benefit of compile time type safety checks, and to preserve developer sanity.
Are there any caveats or gotchas we should be aware of in performing this upgrade?
To use Java generics effectively, you must consider the following restrictions: Cannot Instantiate Generic Types with Primitive Types. Cannot Create Instances of Type Parameters. Cannot Declare Static Fields Whose Types are Type Parameters.
In a nutshell, generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs.
@SuppressWarning("unchecked")
to make warnings go away.Nothing particularly profound here ...
The most important part of the upgrade, IMHO, is to make sure that the developers working on it have a solid understanding of generics, especially with regards to passing Collections into functions and returning them from functions, as List<Animal> <> List<Tiger>
, etc. You should always be able to put in generics, even if you are using the generic Object or ? placeholders.
The other thing that will make the conversion go smooth/not is code dependent, that you have collections that contain a single type, that there aren't mixed objects that force the ? or Object 'catch-alls.' This can be fairly common, especially with Maps.
If you use any underlying libraries, Hibernate, etc, you can run into limitations there if the underlying library does not support generics. In that case, you'll either have to leak the library code through, or wrap the objects (not recommended).
Change the pieces that make sense, leave the pieces that don't, and do it in stages so that you can always roll back a piece if you run into a problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With