Kajal
Kajal

Reputation: 739

How to cast from class type to interface

I have an interface which is implemented by few classes. Based on the full name of the class I want to initialize the class objects.

Interface,

public interface InterfaceSample{
}

Class files,

public class ABC implements InterfaceSample{
}
public class XYZ implements InterfaceSample{
}

A sample test class,

public class SampleManager{
public static InterfaceSample getInstance(String className) {
    InterfaceSample instance = null;
    try {
        instance =  (InterfaceSample) Class.forName(className);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    return instance;
}

} 

I am getting the following error,

 "Cannot cast from Class<capture#1-of ?> to InterfaceSample"

How can I initialize the classes based on its name.

Upvotes: 0

Views: 1375

Answers (2)

merlin2011
merlin2011

Reputation: 75545

You must invoke newInstance() on the class to get an instance.

public class SampleManager{
    public static InterfaceSample getInstance(String className) throws Exception {
        InterfaceSample instance = null;
        try {
            instance =  (InterfaceSample) Class.forName(className).newInstance();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return instance;
    }
} 

Upvotes: 2

LeleDumbo
LeleDumbo

Reputation: 9340

You're almost there:

instance =  (InterfaceSample) Class.forName(className).newInstance();

remember to mark the method with:

throws Exception

because newInstance() is marked so as well (it throws InstantiationException and IllegalAccessException to be precise).

Upvotes: 7

Related Questions