Loading a Class from a String

前端 未结 9 2289
[愿得一人]
[愿得一人] 2020-12-13 09:15

I want to instantiate a class by the value of a String. I found several tutorials that show several methods for doing this. The class MUST inherit from a certain interface

9条回答
  •  悲&欢浪女
    2020-12-13 09:57

    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 instantiate(final String className, final Class 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);
    

提交回复
热议问题