Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unchecked Cast Warning when calling 'Class.forName'

My code is as follows

package com.foo;

public class TestComposition {
    public static void main(String[] args) {
        try {
            Class<Foo> fooClass = 
                    (Class<Foo>) Class.forName("Foo");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

The assignment within the 'try' block results in a warning stating

Type safety: Unchecked cast from Class<capture#1-of ?> to 
     Class<Foo>

Why is this?

like image 398
Joeblackdev Avatar asked Jul 07 '11 11:07

Joeblackdev


1 Answers

Firstly, if you know the exact class then you don't need Class.forName. Foo.class will do. (Prior to J2SE 5.0, Foo.class actually compiled to doing Class.forName("Foo") and then caching it in a static.)

What you probably want is something like:

Class<? extends Foo> fooClass =
    (Class<? extends Foo>) Class.forName("MyFoo");

(When I say want, casts and particularly reflection are evil.)

As it happens, you there is an appropriate method to do the cast "safely" (assuming Foo is not itself generic). Safely as in not providing a reference to an incompatible object, not as in there are no bug or no unexpected exception.

Class<? extends Foo> fooClass =
    Class.forName("MyFoo").asSubclass(Foo.class);
like image 70
Tom Hawtin - tackline Avatar answered Oct 20 '22 04:10

Tom Hawtin - tackline