Rise of the Twitter Clones | Home | Marking Up Forms

Filed under Quick Tips on September 24, 2008 by Doug Burns

Java Quick Tip: Class.forName() with Java Generics

In most cases (Lists, Maps, etc.) the syntax for using Java Generics is pretty straight forward, but for Class.forName(...) that's not the case (at least for me).

Here's an example of how it's done. The first code block is the pre-Generics way. It still works, but results in a compiler warning. The second block is the new Generics way that doesn't generate the warning.

package com.arc90.example;

/**
 * Demonstrates use of Class.forName(...) with Java Generics
 */
public class GenericsExample
{
	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception
	{
		/*
		 * This gives the compiler warning:
		 * "Class is a raw type. References to generic type Class<T> should be parameterized"
		 */
		Class c1 = Class.forName("com.arc90.blog.InstantiateMe");
		ImplementMe i1 = (ImplementMe) c1.newInstance();
		System.out.println(i1.getClass().getName());
		
		/*
		 * This gives no compiler warning
		 */
		Class<? extends ImplementMe> c2 = Class.forName("com.arc90.blog.InstantiateMe").asSubclass(ImplementMe.class);
		ImplementMe i2 = c2.newInstance();
		System.out.println(i2.getClass().getName());
	}
}

To try this yourself you'll need to create two additional classes; An empty interface named ImplementMe and an empty class named InstantiateMe that implements ImplementMe.

Post a Comment Digg Del.icio.us

Trackback Pings (TrackBack URL for this entry)

http://www.arc90.com/cgi-bin/mt4/mt-tb.cgi/193.

Comments

nice post. you can also use Class

Posted on October 15, 2008 5:35 PM by avicene

i meant Class<?>

Posted on October 15, 2008 5:37 PM by avicene

Post a Comment:

Rise of the Twitter Clones | Main | Marking Up Forms