No, there is no better way (by design). You are not supposed to do this, Java is designed as a type-safe language. However, I can understand that you sometimes need to do things like this, and for that purposes you can create a library function like this:
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);
}
}
Now your client code can at least call this method without casting:
MyInterface thingy =
instantiate("com.foo.bar.MyInterfaceImpl", MyInterface.class);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…