Java中鸭子打字的例子是什么? [英] What's an example of duck typing in Java?

查看:144
本文介绍了Java中鸭子打字的例子是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚听说鸭子打字,我读了关于它的维基百科文章,但我我很难将这些示例翻译成Java,这真的有助于我的理解。

I just recently heard of duck typing and I read the Wikipedia article about it, but I'm having a hard time translating the examples into Java, which would really help my understanding.

是否有人能够给出Java中鸭子输入的明确例子以及如何我可能会用它吗?

Would anyone be able to give a clear example of duck typing in Java and how I might possibly use it?

推荐答案

Java的设计并不适合鸭子打字。您可以选择这样做的方式是反射:

Java is by design not fit for duck typing. The way you might choose to do it is reflection:

public void doSomething(Object obj) throws Exception {

    obj.getClass().getMethod("getName", new Class<?>[] {}).invoke(obj);
}

但我会提倡用动态语言来做,比如Groovy,它更有意义:

But I would advocate doing it in a dynamic language, such as Groovy, where it makes more sense:

class Duck {
    quack() { println "I am a Duck" }
}

class Frog {
    quack() { println "I am a Frog" }
}

quackers = [ new Duck(), new Frog() ]
for (q in quackers) {
    q.quack()
}

参考

这篇关于Java中鸭子打字的例子是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆