rdhaese
10/6/2017 - 9:37 AM

Load class by name

Utility method to load a class based on name.

You need no unchecked cast. Just use return type.cast(Class.forName(className).newInstance());. The advantage is that it throws immediately (it's more fail-fast).

public <T> T instantiate(final String className, final Class<T> type){
    try{
        return type.cast(Class.forName(className).newInstance());
    } catch(InstantiationException
          | IllegalAccessException
          | ClassNotFoundException e){
        throw new IllegalStateException(e);
    }
}

MyInterface thingy =
    instantiate("com.foo.bar.MyInterfaceImpl", MyInterface.class);