简体   繁体   English

Java:传递对象实现接口

[英]Java: passing object implementing interface

In Objective-C it is possible to pass a function parameter with type in the form Object<Protocol> which has the meaning "an object of type Object that implements the protocol Protocol". 在Objective-C中,可以传递类型为Object<Protocol>类型的函数参数,其含义是“实现协议Protocol的Object类型的对象”。 I was wondering whether there is a way to do the same in Java, for instance "an Android View that implements some custom interface" (protocol = java interface). 我想知道在Java中是否有一种方法可以做到这一点,例如“实现某些自定义接口的Android View”(协议= java接口)。

You can use generics to specify that the parameter implements an interface: 您可以使用泛型来指定参数实现接口:

public <T extends Protocol> void foo(T t) { ... }

This can be extended to specify multiple bounds. 可以扩展以指定多个范围。 The type must be a subtype of all the specified types. 该类型必须是所有指定类型的子类型。 Object isn't the best example, but here's how you could specify it: Object不是最好的示例,但是可以通过以下方法指定它:

public <T extends Object & Protocol> foo(T t) { ... }

Here's a related tutorial: 这是一个相关的教程:

Oracle Docs - Bounded Type Parameters Oracle Docs-绑定类型参数

Especially note this paragraph: 特别注意这一段:

To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound, which in this example is Number. 要声明一个有界的类型参数,请列出该类型参数的名称,然后是extends关键字,然后是其上限(在本示例中为Number)。 Note that, in this context, extends is used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces). 请注意,在这种情况下,extends通常用于表示“扩展”(如在类中)或“实现”(如在接口中)。

The unexpected part here is that extends is used for interfaces as well. 这里意外的部分是, extends也用于接口。

Note that you can get the desired behaviour without generics as well (see comments below): 请注意,您也可以在没有泛型的情况下获得所需的行为(请参见下面的注释):

public void foo(Protocol p) { ... } 

since this allows for any object that is-a Protocol. 因为这允许对任何对象,它是-一个协议。 If you want to specify multiple interfaces with this approach you could for example create a third interface that implements the other two. 如果要使用此方法指定多个接口,则可以例如创建第三个实现其他两个接口的接口。 However, this assumes that you're in control of the classes that should be able to be passed as arguments since you need to implement that interface. 但是,这假定您在控制应该作为参数传递的类,因为您需要实现该接口。


If you're passing a "regular" generic type parameter you simply specify the type directly: 如果要传递“常规”泛型类型参数,则只需直接指定类型:

public void foo(Object<Protocol> o) {
    // TODO: Implement
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM