Created
August 28, 2011 14:43
-
-
Save asouza/1176751 to your computer and use it in GitHub Desktop.
exemplo of dynamics no scala
This file contains hidden or 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
//para compilar o exemplo faça => scalac arquivo.scala -Xexperimental | |
package br.com.caelum.dynamic | |
import java.util.{GregorianCalendar, Calendar} | |
import java.text.SimpleDateFormat | |
case class Contato(val nome: String, val email: String, val nascimento: Calendar) { | |
override def toString = nome + ";" + email + ";" + new SimpleDateFormat("dd/MM/yyyy").format(nascimento.getTime) | |
} | |
class Agenda extends Dynamic { | |
val contatos = List(Contato("alberto", "[email protected]", new GregorianCalendar(1983, 6, 9)), | |
Contato("adriano", "[email protected]", new GregorianCalendar(1986, 10, 10)), | |
Contato("diego", "[email protected]", new GregorianCalendar(1987, 8, 23)), | |
Contato("cecilia", "[email protected]", new GregorianCalendar(1987, 2, 10))) | |
def applyDynamic(fakeMethodName: String)(args: Any*) = { | |
val FindBy = """(findBy)(\w+)""".r | |
val Like = """(findByLike)(\w+)""".r | |
val Contains = """(findBy)(\w+)(ThatContains)""".r | |
val found = fakeMethodName match { | |
case Like(_, property) => { | |
val realMethodName = lowerFirstLetter(property) | |
contatos.filter(c => invokeMethod[String](c,realMethodName).startsWith(args(0).toString)) | |
} | |
case Contains(_, property, _) => { | |
val realMethodName = lowerFirstLetter(property) | |
contatos.filter(c => invokeMethod[String](c,realMethodName).contains(args(0).toString)) | |
} | |
case FindBy(_, property) => { | |
val realMethodName = lowerFirstLetter(property) | |
contatos.filter(c => invokeMethod[Any](c,realMethodName).equals(args(0))) | |
} | |
case _ => throw new NoSuchMethodException(fakeMethodName) | |
} | |
found | |
} | |
private def invokeMethod[ReturnType](obj:AnyRef,name:String,args: Any*):ReturnType = { | |
obj.getClass.getMethod(name).invoke(obj).asInstanceOf[ReturnType] | |
} | |
private def lowerFirstLetter(propertyWithFirstLetterUpperCase: String) = { | |
propertyWithFirstLetterUpperCase.substring(0, 1).toLowerCase + | |
propertyWithFirstLetterUpperCase.substring(1, propertyWithFirstLetterUpperCase.length) | |
} | |
} | |
object Teste { | |
def main(args: Array[String]) { | |
val agenda = new Agenda | |
println(agenda.findByNome("alberto")) | |
println(agenda.findByEmailThatContains("email.com.br")) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment