Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the caveats of upgrading an app to use Generics in Java?

Tags:

java

generics

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?

like image 954
Mark F Guerra Avatar asked Jun 14 '11 13:06

Mark F Guerra


People also ask

What are the restrictions on generics in Java programming?

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.

What is generics in Java What are advantages of using generics?

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.


2 Answers

  1. Understand how Java generics work, and their limitations.
  2. Use an IDE with good refactoring support.
  3. Do it slowly and carefully.
  4. Do the simple things first, and don't leap into creating complicated generic classes, etc until you know they are really required.
  5. Resist the temptation to add @SuppressWarning("unchecked") to make warnings go away.

Nothing particularly profound here ...

like image 106
Stephen C Avatar answered Nov 14 '22 22:11

Stephen C


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.

like image 43
Steven Mastandrea Avatar answered Nov 14 '22 22:11

Steven Mastandrea