Java Generics with legacy code
by , 11-15-2011 at 06:31 PM (748 Views)
In this post, I will write about how Java generics help us in using legacy code.
Generics are new in Java and now developers understand the importance of it and it is being used as required. Question arises, what about the legacy code? Consider an IT firm that is working on an application for 5 years, and they used Java 1.4 for development. They the plan to use 1.5 for development simply because it is better than 1.4. Are they supposed to convert the old code to 1.5 also? This is not practical, as it requires a lot of efforts and time. We may use older code with generics but definitely there will be some warnings. Lets take an example:
Legacy code:
Java Code:public interface University { public void setStudents(Collection c); public Collection getStrudents(); } public class UniImpl implements University{ private Collection students; public UniImpl(){ students = new ArrayList(); } public Collection getStudents() { return students; } public void setStudents(Collection c) { this.students = c; } }
We have an interface and its implementation (see the previous post). Thing to note is that we are using a collection without any type. Assume that this code was written using JDK 1.4. We have getter and setter methods for the collection.
New code:
Here we make object of legacy class called UniImpl. Then we make a collection of String type and added data to it. We then called setter method of UniImpl class and passed it a collection object of type String. There was no error or warning there. All is ok so far. Then we called the getter method in order to get the collection. We got a warning saying:Java Code:public static void main(String[] args) { UniImpl obj = new UniImpl(); Collection c = new ArrayList(); c.add("Laiq"); c.add("Farjad"); c.add("Dave"); c.add("Mike"); c.add("Ken"); obj.setStudents(c); c = obj.getStrudents(); for(String str:c ) { System.out.println("Student: " + str); } }
ArrayList is a raw type. References to generic type ArrayList should be parameterized
Compiler generated warning because it cannot guarantee its correctness. We are trying to get a collection of no type into a collection of type String. Compiler has no idea about the type of collection that getStudents method of UniImpl class will return.









Email Blog Entry
Size Reduced for Images in PDF &...
05-15-2013, 05:53 PM in Java Software