使用Reflection在Abstract Class中创建一个实例 [英] Create an instance within Abstract Class using Reflection

查看:127
本文介绍了使用Reflection在Abstract Class中创建一个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用反射
在抽象祖先类中创建派生类的实例让我们说:

Is it possible to create an instance of a derived class in abstract ancestor class using reflection Lets say:

abstract class Base {

public Base createInstance(){
  //using reflection
    Class<?> c = this.getClass();
    Constructor<?> ctor = c.getConstructor();
    return ((Base) ctor.newInstance());
}

}//end Base

class Derived extends Base {

 main(){

new Derived().createInstance()

 }

}

推荐答案

你可以这样做

public class Derived extends Base {
    public static void main(String ... args) {
        System.out.println(new Derived().createInstance());
    }
}

abstract class Base {
    public Base createInstance() {
        //using reflection
        try {
            return getClass().asSubclass(Base.class).newInstance();
        } catch (Exception e) {
            throw new AssertionError(e);
        }
    }
}

打印

Derived@55fe910c

更常见的模式是使用Cloneable

A more common pattern is to use Cloneable

public class Derived extends Base {
    public static void main(String ... args) throws CloneNotSupportedException {
        System.out.println(new Derived().clone());
    }
}

abstract class Base implements Cloneable {
    @Override
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

打印

Derived@8071a97

然而,需要应该避免使用任何一种。通常还有另一种方法可以做你需要的事情,这样基数就不会隐含地依赖于派生。

However, the need to use either should be avoided. Usually there is another way to do what you need so that base doesn't not implicitly depend on derived.

这篇关于使用Reflection在Abstract Class中创建一个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆