New instance of class based on argument

后端 未结 4 485
时光说笑
时光说笑 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:26

    Are you passing a Class object as the parameter, or in instance of a subclass of Foo?

    The solution is almost the same in either case, you use the newInstance method on the Class object.

    /**
     * Return a new subclass of the Foo class.
     */
    public Foo fooFactory(Class c)
    {
        Foo instance = null;
        try {
            instance = c.newInstance();
        }
        catch (InstantiationException e) {
            // ...
        }
        catch (IllegalAccessException e) {
            // ...
        }
        return instance; // which might be null if exception occurred,
                         // or you might want to throw your own exception
    }
    

    If you need constructor args you can use the Class getConstructor method and from there the Constructor newInstance(...) method.

提交回复
热议问题