【问题标题】:New instance of class based on argument基于参数的类的新实例
【发布时间】:2012-01-28 01:52:03
【问题描述】:

我正在尝试创建一个函数,该函数采用扩展Foo 的众多类之一,并在其类中返回该对象的新实例,而不是Foo 的新实例。

我确定这是一个常见问题。有什么好的例子吗?

我从来没有使用类作为输入参数,只有类的成员。根据我搜索的内容,这应该可以做到吗?

【问题讨论】:

    标签: java


    【解决方案1】:

    您是传递Class 对象作为参数,还是传递Foo 的子类实例?

    这两种情况的解决方案几乎相同,您在 Class 对象上使用 newInstance 方法。

    /**
     * Return a new subclass of the Foo class.
     */
    public Foo fooFactory(Class<? extends Foo> 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
    }
    

    如果您需要构造函数参数,您可以使用 Class getConstructor 方法,然后从那里使用构造函数 newInstance(...) 方法。

    【讨论】:

    【解决方案2】:

    你的函数可能是这样的

    public class NewInstanceTest {
        public static Object getNewInstance(Foo fooObject){
            java.lang.Class fooObjectClass = fooObject.getClass();
            try {
                return fooObjectClass.newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
                return null;
            } catch (IllegalAccessException e) {
                e.printStackTrace();
                return null;
            }
     }
     public static void main(java.lang.String[] args){
            // This prints Foo
            java.lang.System.out.println(getNewInstance(new Foo()).getClass().getName());
            // This prints Foo1
            java.lang.System.out.println(getNewInstance(new Foo1()).getClass().getName());
     }
    }
    class Foo{
    }
    class Foo1 extends Foo{
    }
    

    希望这会有所帮助。

    【讨论】:

      【解决方案3】:

      查看Abstract Factory 模式。

      【讨论】:

        【解决方案4】:

        你可以在这里使用Java的反射。

        如果您想通过类名获得Class,请使用Class.forName

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

        你可以检查这个类是Foo还是它的子类:

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

        然后您可以非常轻松地创建一个新实例(假设构造函数不带参数):

        Object instance = type.newInstance();
        

        【讨论】:

          猜你喜欢
          • 2018-01-03
          • 2021-02-02
          • 2020-08-30
          • 2016-12-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-09-01
          相关资源
          最近更新 更多