Example of Duck Typing in Java

588 views Asked by At

I have been reading examples of representations of Duck Typing in Java with reflection. I would like to know if this is correct:

public interface Quackable {
    public void quack();
}

In main...

Object[] vec = {(Here I add some instances)};

for(int i=0; i < vec.length; i++) {
    if(vec[i] instanceof Quackable)
        vec[i].quack();
}
1

There are 1 answers

0
Grzegorz Żur On BEST ANSWER

There is no duck typing in Java as it is in Python. You can use reflection to find if the class has a method you want to call but it is really a hassle.

It looks like that

Class<?> aClass = object.getClass();
try {
    Method method = aClass.getMethod("methodName", argType1, argType2);
    method.invoke(arg1, arg2)
} catch (NoSuchMethodException | SecurityException e) {
    e.printStackTrace();
}

It is also not possible in every environment. If security manager is enabled your code should have sufficient rights to execute the code above. That also adds substantial work.