New instance of class based on argument

后端 未结 4 437
时光说笑
时光说笑 2021-01-26 15:23

I\'m trying to make a function that takes one of many classes that extends Foo, and return a new instance of that object in its Class, not a new instance of F

4条回答
  •  天涯浪人
    2021-01-26 15:25

    You can use Java's reflection here.

    If you want to get a Class by just its classname, you use Class.forName:

    Class type = Class.forName('package.SomeClass');
    

    You can check if this class is Foo or a subclass of it:

    boolean isFoo = type.isAssignableFrom(Foo.class);
    

    You can then create a new instance very easily (assuming the constructor takes no arguments):

    Object instance = type.newInstance();
    

提交回复
热议问题