Pass your class as a parameter and avoid casting

This is really really cool. Did you know you can define the return type of a method based on one of its parameters?

Here’s a little piece of code that takes a URI and then deserializes an XML file into an object. Notice in this first code snippit there is an explicit typecast to (FooServer) in front of the call to readXMLConfigFile(fooServerURI) since we need to re-use readXMLConfigFile() to deserialize many different object types from XML.

public FooServer getFooServer() {
		if (fooServer == null) {
			fooServer = (FooServer)readXMLConfigFile(fooServerURI);
		}
		return fooServer;
	}

	private Object readXMLConfigFile(String uriString) {
		Object retval = null;
		Serializer serializer = new Persister();
		URI uri = new URI(uriString);
		File source = new File(uri);
		retval = serializer.read(type, source);
		return retval;
	}

So here’s the magic. You can pass in a paramter that defines for the compiler the return type of the method by how it is invoked. Look ma! No more typecasts!

public FooServer getFooServer() {
		if (fooServer == null) {
			fooServer = readXMLConfigFile(FooServer.class, fooServerURI);
		}
		return fooServer;
	}

	private <T> T readXMLConfigFile(Class<? extends T> type, String uriString) {
		T retval = null;
		Serializer serializer = new Persister();
		URI uri = new URI(uriString);
		File source = new File(uri);
		retval = serializer.read(type, source);
		return retval;
	}

How did I discover this? Well to deserialize my XML I’m using a very slick little tool with the unfortunate name of “Simple XML” (try searching for that in Google–good luck). Here’s the URL to save you the trouble: http://simple.sourceforge.net. You couldn’t ask for a cleaner annotation based XML mapping framework. Anyways, I noticed when I called their serializer.read() method that the compiler didn’t complain that I didn’t explicitly typecast the return value to my type. So I followed Obi Wan Kenobi’s advice (“Use the Source Luke”) and found out how they did it. Pretty cool eh?

It's only fair to share...
Share on FacebookGoogle+Tweet about this on TwitterShare on LinkedIn

Leave a Reply