-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMethodDiscovery.scala
42 lines (35 loc) · 1023 Bytes
/
MethodDiscovery.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import java.lang.reflect.Method
/**
* A simple object that lets you discover the capabilities of other objects
* without referring to documentation immediately. Inspired by Ruby's elegant reflection.
*
* Usage:
* import MethodDiscovery._
*
* val aString = "Hello, folks"
* namesOf(methods(aString))
* signaturesOf(methods(aString))
*
*/
object MethodDiscovery {
def methods(o: AnyRef): List[Method] = {
List.fromArray(o.getClass.getMethods)
}
def declaredMethods(o: AnyRef): List[Method] = {
List.fromArray(o.getClass.getDeclaredMethods)
}
def namesOf(l: List[Method]): List[String] = {
sort(l.map(m => m.getName))
}
def signaturesOf(l: List[Method]): List[String] = {
sort(l.map(formatSig))
}
def sort(l: List[String]): List[String] = {
l.sort((a, b) => (a compareTo b) < 0 )
}
def formatSig(m: Method): String = {
m.getName +
List.fromArray(m.getParameterTypes).map(c => c.getName).mkString("(", ", ", "): ") +
m.getReturnType.getName
}
}