如何在scala中获取方法列表 [英] How to get methods list in scala
问题描述
在像python和ruby这样的语言中,询问该语言其字符串类支持哪些与索引相关的方法(哪些方法的名称包含索引"一词)你可以做
In language like python and ruby to ask the language what index-related methods its string class supports (which methods’ names contain the word "index") you can do
"".methods.sort.grep /index/i
在Java中
List results = new ArrayList();
Method[] methods = String.class.getMethods();
for (int i = 0; i < methods.length; i++) {
Method m = methods[i];
if (m.getName().toLowerCase().indexOf("index") != -1) {
results.add(m.getName());
}
}
String[] names = (String[]) results.toArray();
Arrays.sort(names);
return names;
你会如何在 Scala 中做同样的事情?
How would you do the same thing in Scala?
推荐答案
好奇没有人尝试过更直接的翻译:
Curious that no one tried a more direct translation:
""
.getClass.getMethods.map(_.getName) // methods
.sorted // sort
.filter(_ matches "(?i).*index.*") // grep /index/i
所以,一些随机的想法.
So, some random thoughts.
方法"和上面的圈套之间的区别是惊人的,但从来没有人说反射是 Java 的强项.
The difference between "methods" and the hoops above is striking, but no one ever said reflection was Java's strength.
我在上面隐藏了一些关于 sorted
的东西:它实际上需要一个 Ordering
类型的隐式参数.如果我想对方法本身而不是它们的名称进行排序,我必须提供它.
I'm hiding something about sorted
above: it actually takes an implicit parameter of type Ordering
. If I wanted to sort the methods themselves instead of their names, I'd have to provide it.
grep
实际上是 filter
和 matches
的组合.由于 Java 决定匹配整个字符串,即使未指定 ^
和 $
,这使得它变得有点复杂.我认为在 Regex
上有一个 grep
方法是有意义的,它以 Traversable
作为参数,但是...
A grep
is actually a combination of filter
and matches
. It's made a bit more complex because of Java's decision to match whole strings even when ^
and $
are not specified. I think it would some sense to have a grep
method on Regex
, which took Traversable
as parameters, but...
所以,这是我们可以做的:
So, here's what we could do about it:
implicit def toMethods(obj: AnyRef) = new {
def methods = obj.getClass.getMethods.map(_.getName)
}
implicit def toGrep[T <% Traversable[String]](coll: T) = new {
def grep(pattern: String) = coll filter (pattern.r.findFirstIn(_) != None)
def grep(pattern: String, flags: String) = {
val regex = ("(?"+flags+")"+pattern).r
coll filter (regex.findFirstIn(_) != None)
}
}
现在这是可能的:
"".methods.sorted grep ("index", "i")
这篇关于如何在scala中获取方法列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!