scala 如何在scala中获取方法列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2886446/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get methods list in scala
提问by skyde
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
在像 python 和 ruby 这样的语言中,询问语言它的字符串类支持哪些与索引相关的方法(哪些方法的名称包含“索引”一词)你可以做
“”.methods.sort.grep /index/i
And in java
在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;
How would you do the same thing in Scala?
你会如何在 Scala 中做同样的事情?
回答by Daniel C. Sobral
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.
所以,有些胡思乱想。
The difference between "methods" and the hoops above is striking, but no one ever said reflection was Java's strength.
I'm hiding something about
sortedabove: it actually takes an implicit parameter of typeOrdering. If I wanted to sort the methods themselves instead of their names, I'd have to provide it.A
grepis actually a combination offilterandmatches. 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 agrepmethod onRegex, which tookTraversableas parameters, but...
“方法”和上面的圈套之间的区别是惊人的,但从来没有人说反射是 Java 的强项。
我在
sorted上面隐藏了一些东西:它实际上需要一个隐式参数 typeOrdering。如果我想对方法本身而不是它们的名称进行排序,我必须提供它。A
grep实际上是filter和的组合matches。由于 Java 决定匹配整个字符串,即使^和$未指定,它也变得有点复杂。我认为在 上有一个grep方法是有意义的Regex,它Traversable作为参数,但是......
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)
}
}
And now this is possible:
现在这是可能的:
"".methods.sorted grep ("index", "i")
回答by Saichovsky
You can use the scala REPL prompt. To find list the member methods of a string object, for instance, type "". and then press the TAB key (that's an empty string - or even a non-empty one, if you like, followed by a dot and then press TAB). The REPL will list for you all member methods.
您可以使用 scala REPL 提示。例如,要查找字符串对象的成员方法列表,请键入“”。然后按 TAB 键(这是一个空字符串 - 或者甚至是非空字符串,如果您愿意,后跟一个点,然后按 TAB)。REPL 将为您列出所有成员方法。
This applies to other variable types as well.
这也适用于其他变量类型。
回答by sblundy
More or less the same way:
或多或少相同的方式:
val names = classOf[String].getMethods.toSeq.
filter(_.getName.toLowerCase().indexOf(“index”) != -1).
map(_.getName).
sort(((e1, e2) => (e1 compareTo e2) < 0))
But all on one line.
但都在一条线上。
To make it more readable,
为了使其更具可读性,
val names = for(val method <- classOf[String].getMethods.toSeq
if(method.getName.toLowerCase().indexOf("index") != -1))
yield { method.getName }
val sorted = names.sort(((e1, e2) => (e1 compareTo e2) < 0))
回答by OscarRyz
Now, wait a minute.
现在,等一下。
I concede Java is verbose compared to Ruby for instance.
例如,我承认 Java 与 Ruby 相比显得冗长。
But that piece of code shouldn't have been so verbose in first place.
但是那段代码本来就不应该如此冗长。
Here's the equivalent :
这是等效的:
Collection<String> mds = new TreeSet<String>();
for( Method m : "".getClass().getMethods()) {
if( m.getName().matches(".*index.*")){ mds.add( m.getName() ); }
}
Which has almost the same number of characters as the marked as correct, Scala version
它的字符数与标记为正确的 Scala 版本几乎相同
回答by OscarRyz
This is as far as I got:
这是我得到的:
"".getClass.getMethods.map(_.getName).filter( _.indexOf("in")>=0)
It's strange Scala array doesn't have sort method.
奇怪的是 Scala 数组没有排序方法。
edit
编辑
It would end up like.
它最终会像。
"".getClass.getMethods.map(_.getName).toList.sort(_<_).filter(_.indexOf("index")>=0)
回答by pdbartlett
Just using the Java code direct will get you most of the way there, as Scala classes are still JVM ones. You could port the code to Scala pretty easily as well, though, for fun/practice/ease of use in REPL.
直接使用 Java 代码可以让您获得大部分方法,因为 Scala 类仍然是 JVM 类。不过,为了在 REPL 中有趣/练习/易于使用,您也可以很容易地将代码移植到 Scala。

