There was an error in this gadget

Wednesday, March 21, 2012

Java Introspection and Using Collections without Generics

In my prior article on Generics we looked at how to use Generics to associate at type with data stored in a Collection.

You might wonder why would anyone want to store information in a Collection without its type being preserved. Well, it's possible that you'd want to store many Objects of different types in one collection. In that case, the only parent those types might have in common is java.lang.Object. So using a Generic won't do you any good.

But, once you pull that data back out of the Collection, how do you find out what it was?

Fortunately, the object itself has that information stored with it.

There are two easy ways to find out what it is. instanceof can test if it is a specific type of Object:

if (anObject instanceof String) { aString = (String)anObject); }

You can also have an Object tell you its type:

Class myClass = anObject.getClass();


String myClassName = anObject.getClass().getName();

A look at the documentation for Object and Class gives all sorts of useful methods for dealing with classes of data objects in Java.

Here's some sample code:

import java.util.*;

public class NoGenerics2{
// This is an example of using introspection
// to determine types of Objects stored in a
// Collection without a Generic declaration.

public static void main(String[] arg){
ArrayList myList = new ArrayList(); // No Generic declaration.
String myString="Boss Moss";
String yourString="Snorkledorf";

// put the strings into the List

for (Object anObject: myList){
if (anObject instanceof String){
String aString = (String)anObject;
System.out.println("Not a String, Sheriff!");