by ighost on 2/4/10, 1:54 AM with 23 comments
by ZitchDog on 2/4/10, 2:47 AM
class ObjectUtil {
static boolean hasMethod(Object obj, String... methodNames) {
for(String methodName : methodNames)
if(!hasMethod(obj, methodName))
return false;
return true;
}
static boolean hasMethod(Object obj, String methodName) {
for(Method method : obj.getClass().getMethods())
if(method.getName().equals(methodName))
return true;
return false;
}
}
by jerf on 2/4/10, 2:29 AM
I'm not speaking to whether dynamic/duck typing is good or bad here, just pointing out that the question is flawed.
by patio11 on 2/4/10, 2:30 AM
My gut check was this should take about eight lines, plus imports and the class boilerplate. Let's try:
Yep, eight.
[Edit: It occurs to me the Python code might answer "Does this implement all specified methods?" That also takes eight lines in Java. I've appended the implementation above.]
by efsavage on 2/4/10, 3:30 AM
by brehaut on 2/4/10, 2:39 AM
def hasmethod(obj, meth_name):
"""If it calls like a method it's a method."""
return callable(getattr(obj, meth_name)) if hasattr(obj, meth_name) else False
by jashkenas on 2/4/10, 2:14 AM
has_methods: (obj, meth_names) ->
name for name in meth_names when obj[name] and obj[name].call
by pyman on 2/4/10, 4:54 PM