【问题标题】:How do you require a parameter to be a class implementing an interface?您如何要求参数成为实现接口的类?
【发布时间】:2015-12-01 07:19:22
【问题描述】:

我知道你可以在方法中要求一个类的子类

method(Class<? extends Object> var)

但是我需要方法来接收实现某个接口的参数,实际上是两个接口

method(Class<? implements Interface, Interface2> var)

这在 Android/Java 中可行吗?

【问题讨论】:

    标签: java android methods interface


    【解决方案1】:

    如果您有一个接口的实例,这要求相关对象是“子对象”。这应该做你想做的事

    method(NameOfInterface1 var1, NameOfInterface2 var2){ stuff...}
    

    例如,假设我有一个接口“Person”和一个实现“Person”的类“Bob”。那么

    method(Person var1, Person var2) { stuff... }
    

    此方法将接受所有实现 Person 的类,包括 Bob。

    编辑。

    假设您希望该方法接受实现两个接口的参数,您可以创建第三个接口,这样

    interface Interface3 extends Interface1, Interface2
    

    然后创建实现 Interface3 的子节点

    【讨论】:

    • interface Interface3 extends Interface1, Interface2 这个 Interface3 可以用作参数的类型吗?
    • 在 Java/Android 中,您不能创建接口的实例,即通过调用 new Interface3()。但是,您可以执行以下 Interface3 i = new ClassImplementingInterfac3();。然后,您可以将 i 作为参数传递给接受 Interface3 类型对象的方法。所以 tldr 是肯定的,你可以。但最终传递给方法的对象必须是实现接口的类型(本例中为Interface3)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-25
    • 2019-03-04
    • 1970-01-01
    • 2018-05-12
    • 1970-01-01
    相关资源
    最近更新 更多