[英]Java: Return an object that extends an abstract class which takes arguments
I've got an interface 我有一个界面
public interface I
{
public AnAbstractClass k(); //Abstract Class constructor takes two arguments
}
For an implementation of this interface's method I want to return a generic object which extends that AbstractClass and also give it its two argument constructor 对于这个接口的方法的实现,我想返回一个扩展AbstractClass的通用对象,并给它两个参数构造函数
To clarify what I want to achieve. 澄清我想要实现的目标。 In a class which implements I: 在实现I的类中:
public AnAbstractClass k()
{
//return a new implementing AbstractClass object AbstractClassObject(arg1,arg2)
}
Constructors are not inherited, so subclasses of AnAbstractClass
won't necessarily have a two-argument constructor. 构造函数不是继承的,因此AnAbstractClass
子类不一定具有双参数构造函数。 If a subclass does have a two-argument constructor, there is nothing stopping you from creating an instance of that subclass using the two-argument constructor and returning it: 如果一个子类确实有一个双参数构造函数,那么就没有什么能阻止你使用双参数构造函数创建该子类的实例并返回它:
public abstract class AnAbstractClass
{
public AnAbstractClass(String foo, String bar) {
System.out.format("created with (%s, %s)\n", foo, bar);
}
}
public class BaseClass extends AnAbstractClass
{
public BaseClass(String foo, String bar) {
super(foo, bar);
}
}
public interface I
{
public AnAbstractClass k();
}
public class Implementation implements I
{
@Override public AnAbstractClass k() {
return new BaseClass("hello", "world");
}
}
public class Demo
{
public static void main(String[] args) {
I i = new Implementation();
AnAbstractClass a = i.k();
}
}
There are sophisticated solutions for this problem (roughly: Everything that is related to dependency injection). 对于这个问题有很复杂的解决方案(粗略地说:与依赖注入相关的一切)。 However, in this case, there are not so many options: Someone HAS to provide these arguments, and they obviously can not be passed to the interface method. 但是,在这种情况下,没有那么多选项:有人提供这些参数,而且它们显然无法传递给接口方法。 So you'll probably need something like 所以你可能需要类似的东西
class Creator implements I
{
private Object arg0;
private Object arg1;
void setArgs(Object arg0, Object arg1)
{
this.arg0 = arg0;
this.arg1 = arg1;
}
@Override
public AnAbstractClass k()
{
return new ConcreteClassExtendingAnAbstractClass(arg0, arg1);
}
}
The drawback is that this interface might become more or less useless: If it was designed to be a factory, you can no longer use it in its abstract form... 缺点是这个界面可能或多或少变得无用:如果它被设计成一个工厂,你就不能再以它的抽象形式使用它......
I i = obtainFromSomewhere();
AnAbstractClass a = i.k();
but you always have to know the particular type 但你总是要知道特定的类型
Creator i = obtainFromSomewhere();
i.setArgs(..., ...);
AnAbstractClass a = i.k();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.