[英]java: pass an object and return same object's type
I have an abstract class A 我有一个抽象类A
public astract class A{
public abstract A f(A a) throws IllegalArgumentException;
};
but I want object a passed to f to have the same type of the object itself and return an object of same type, otherwise throw an IllegalArgumentException. 但我希望传递给f的对象具有与对象本身相同的类型,并返回相同类型的对象,否则抛出IllegalArgumentException。 How can I implement that one time for all subclasses?
如何一次为所有子类实现该功能? There is a way to do that at the class A level?
有办法在A级水平上做到这一点吗?
Java does not provide a way to state this requirement declaratively. Java没有提供一种声明式声明此要求的方法。 However, you can make a run-time check at the level of your abstract class by following the Template Method design pattern:
但是,您可以按照“ 模板方法”设计模式在抽象类级别进行运行时检查:
public abstract class A {
public final A f(A a) {
if (a.getClass() != this.getClass()) {
throw new IllegalArgumentException();
}
A res = fImpl(a);
if (res.getClass() != this.getClass()) {
throw new InvalidOperationException();
}
return res;
}
protected abstract A fImpl(A a); // Implementing classes put functionality here
}
The above code changes f(A)
from abstract method to template method by providing shared functionality for all subclasses of A
. 上面的代码通过为
A
所有子类提供共享功能,将f(A)
从抽象方法更改为模板方法 。 In this case the shared functionality is argument checking, and also the return type checking. 在这种情况下,共享功能是参数检查以及返回类型检查。
This is the method that the clients of your class are going to use. 这是类的客户端将要使用的方法。 The implementors of the abstract class, on the other hand, will be implementing
fImpl
method, which can assume that its argument A
is a subclass that matches their own class. 另一方面,抽象类的实现者将实现
fImpl
方法,该方法可以假定其参数A
是与自己的类匹配的子类。
public abstract class A
{
public A f(A a) throws IllegalArgumentException
{
if (!this.getClass().equals(a.getClass()))
{
throw new IllegalArgumentException();
}
return a;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.