2017-05-18 51 views
-1

语言:Java我可以通过通用接口类型作为参数方法

所以我有一堆中间件自动生成的接口文件。他们都有我想要访问的类似结构。有没有一种方法可以在方法中交替使用它们。同样的事情也该

private void setDataToInterfaceFile(String dataTobeSet,Interface interface){ 
    interface.setString(dataTobeSet) 
} 

和使用本这样的事情

setDataToInterface("Set me to 1",Interface_1) 
setDataToInterface("Set me to 2",Interface_2) 
+1

无法将数据设置为接口,可能需要传递实现接口的类的实例 –

+0

yes是因为接口只有方法签名,但类和抽象类具有方法的实现 –

+0

如果'interface'被命名为'接口“(这将是一个可怕的选择名称)和”Interface_1“,”接口2“和”接口“(你必须重新命名,如bradimus所提到的)是'Interface'类型,那么是的, (尽管这些名称....)。 – Turing85

回答

1

setDataToInterface( “我的设置1”,Interface_1)

Interface_1不是接口本身。它是实现接口的类的一个实例。

一个类的实现可以有多个接口。这个接口可以用相同的签名来声明方法。

一个额外的接口中声明的所有自动生成的接口的“类似结构”:

interface Interface 
{ 
    void setString(String text); 
} 

然后自动生成Interface_1

class Interface_1_Impl implements Interface, Interface_1 
{ 
    @Override 
    public void setString(String text) 
    { 
    // ... 
    } 
} 

可以作为的实现参数setDataToInterfaceFile()

此设计模式被称为类适配器

相关问题