TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

How many lines of Java would this take?

8 点作者 ighost超过 15 年前

7 条评论

ZitchDog超过 15 年前
<p><pre><code> 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; } }</code></pre>
jerf超过 15 年前
None. Even with Java's typesystem you can know whether the thing or things you have in your hand implements some interface or not ("callable" in this case) at compile time. You can't ask this question because you can't not already know the answer.<p>I'm not speaking to whether dynamic/duck typing is good or bad here, just pointing out that the question is flawed.
评论 #1099610 未加载
评论 #1099634 未加载
评论 #1099643 未加载
patio11超过 15 年前
[Disclaimer: I don't read Python, but I <i>think</i> the question here is "Which methods from this list does this object implement?" If I'm wrong please correct me.]<p>My gut check was this should take about eight lines, plus imports and the class boilerplate. Let's try:<p><a href="http://www.pastie.org/808727" rel="nofollow">http://www.pastie.org/808727</a><p>Yep, eight.<p>[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.]
评论 #1099622 未加载
efsavage超过 15 年前
I don't really care how many lines of Java this takes, if someone commits a garbage scenario like this I'm concerned with how many lines of comments they have explaining why they're doing it instead of solving the problem correctly.
brehaut超过 15 年前
The snippet is imprecise. it should be something like<p><pre><code> 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</code></pre>
评论 #1099636 未加载
jashkenas超过 15 年前
In CoffeeScript, it's a few lines less:<p><pre><code> has_methods: (obj, meth_names) -&#62; name for name in meth_names when obj[name] and obj[name].call</code></pre>
评论 #1099586 未加载
pyman超过 15 年前
Idiots count lines, programmers write them