Created
April 28, 2011 19:25
-
-
Save p3t0r/947112 to your computer and use it in GitHub Desktop.
example of encoding parameters in the methodname using the Dynamic trait
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.log4.methodmissing | |
import java.lang.Integer | |
class ParameterInMethodNameExample extends Dynamic { | |
def find(by:String, value:String) = "select from users where %s = '%s'".format(by, value) | |
def find(by:String, value:Integer) = "select from users where %s = %s".format(by, value) | |
def delete(by:String, value:String) = "delete from users where %s = '%s'".format(by, value) | |
def delete(by:String, value:Integer) = "delete from users where %s = %s".format(by, value) | |
def applyDynamic(methodName: String)(args: Any*) = { | |
WordUtils.decamelize(methodName) match { | |
case x :: xs if xs.contains("by") => { | |
val invokeArgs = List(xs.last, args.head) | |
val result = getClass.getMethod(x, invokeArgs.map(_.asInstanceOf[AnyRef].getClass): _*) // self-reflection | |
.invoke(this, invokeArgs.map(_.asInstanceOf[AnyRef]) : _*) | |
println(result) | |
} | |
case _ => throw new UnsupportedOperationException | |
} | |
} | |
} | |
object ParameterInMethodNameExample { | |
def main(args: Array[String]) { | |
val inMethodNameExample = new ParameterInMethodNameExample | |
inMethodNameExample.findByName("peter") // <-- calls find("name", "peter") | |
inMethodNameExample.findById(1234) // <-- calls find("id", 1234) | |
inMethodNameExample.deleteById(123345) // <-- calls delete("id", 123345) | |
inMethodNameExample.deleteWhereId(123) // <-- doesn't match pattern, throw USOE | |
} | |
} | |
object WordUtils { | |
def decamelize(s: String) = { // from http://stackoverflow.com/questions/2559759 | |
s.replaceAll("%s|%s|%s".format("(?<=[A-Z])(?=[A-Z][a-z])", "(?<=[^A-Z])(?=[A-Z])", "(?<=[A-Za-z])(?=[^A-Za-z])"), ",").toLowerCase.split(",").toList | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment