Loading a Class from a String

前端 未结 9 2276
[愿得一人]
[愿得一人] 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 10:03

    In all essence that is what will happen regardless of whether you're using a third party toolkit for it or not. Casting the object will inherently be mandatory unless expecting an Object. You can however make a routine which does that for you:

    public  T instantiateObject(String name, Class cls) throws Exception {
        return (T) Class.forName(name).newInstance();
    }
    

    Which you can use:

    AClass cls = instantiateObject("com.class.AClass", AClass.class);
    

    But if you come this far, the String name is actually redundant (given AClass is a concrete class). You might as well:

    public  T instantiateObject(Class cls) throws Exception {
        return (T) Class.forName(cls.getCanonicalName()).newInstance();
    }
    

    Which you can use:

    AClass cls = instantiateObject(AClass.class);
    

提交回复
热议问题