Wednesday, September 24th, 2008

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

By Doug Burns

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.

2 Responses

  1. 10/15/2008
    avicene Said:

    nice post. you can also use Class

  2. 10/15/2008
    avicene Said:

    i meant Class<?>

Leave a Comment