假设我有一个类,我想向其中添加一个属性。该属性的值应该实现某个接口(interface)。然而,我根本不关心它是什么类型的对象/类,只要它实现了某个接口(interface)的方法即可。
有办法实现这种行为吗?
在 Objective-C 中,我会这样做:
@property (nonatomic, strong) id <MyInterface> attr;
最佳答案
将类中的字段声明为接口(interface)的类型:
public class YourClass {
private MyInterface attr;
}
对象引用所属的类并不重要,仅重要的是该类是否实现了所需的接口(interface)。这是一个例子:
public class MyClass {
private List<String> stringList;
public void setStringList(List<String> stringList) {
this.stringList = stringList;
}
}
//...
MyClass myClass = new MyClass();
myClass.setStringList(new ArrayList<String>());
myClass.setStringList(new LinkedList<String>());
来自您的评论:
I don't think of Interfaces as types. More like a feature an object has.
在 Java 中,接口(interface)是一种类型。如果您希望某种类型同时声明两个接口(interface),您可以创建从这两个接口(interface)扩展的第三个接口(interface):
interface ThirdPartyInterface1 {
}
interface ThirdPartyInterface2 {
}
interface MyInterface extends ThirdPartyInterface1, ThirdPartyInterface2 {
}
public class YourClass {
private MyInterface attr;
}
关于实现某个接口(interface)的Java属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23566383/