使用反射访问抽象基类的构造函数 [英] Accessing constructor from abstract base class with reflection

查看:180
本文介绍了使用反射访问抽象基类的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在玩Java的反思。我有一个抽象类 Base 与构造函数。

I'm playing around with Java's Reflection. I have an abstract class Base with a constructor.

abstract class Base {
    public Base( String foo ) {
        // do some magic
    }
}

我还有一些扩展 Base 的类。他们不包含太多逻辑。我想用 Base 的构造函数来实例化它们,而不必在这些派生类中编写一些代理构造函数。当然,我想用Reflection来实例化这些派生类。说:

I have some further classes extending Base. They don't contain much logic. I want to instantiate them with Base's constructor, without having to write some proxy contructors in those derived classes. And of course, I want to instantiate those derived classes with Reflection. Say:

Class cls = SomeDerivedClass.class;
Constructor constr;
constr = cls.getConstructor( new Class[] { String.class } ); // will return null
Class clsBase = Base.class;
constr = clsBase.getConstructor( new Class[] { String.class } ); // ok
Base obj = (Base) constr.newInstance( new Object[] { "foo" } ); // will throw InstantiationException because it belongs to an abstract class

任何想法,类与Base的构造函数?

Any ideas, how I can instantiate a derived class with Base's constructor? Or must I declare those dumb proxy constructors?

推荐答案

类不会从父类继承构造函数。一个类没有父类的构造函数(虽然它可以调用它们)所以你必须调用该类的构造函数,而不是一个超类的构造函数。

A class does not inherit constructors from it parent. A class does not have it parents constructors (though it can call them) So you have to call the constructors the class has, not a constructor a super class has.

默认构造函数只显示这样做,因为它默认调用父的默认构造函数。如果父级没有默认构造函数,它的直接子级也不能。

The default constructor only appears to do this because it calls the default constructor of the parent by default. If the parent doesn't have a default constructor, neither can its immediate children.

这篇关于使用反射访问抽象基类的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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