Created
February 3, 2021 21:32
-
-
Save nafg/3148b4a12992dae629815efcc95cf1db to your computer and use it in GitHub Desktop.
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
import java.beans.Introspector | |
import java.nio.file.{Files, Paths} | |
object GenerateBeanCaseClass extends App { | |
val typeRenderings = Map[Class[_], String]( | |
classOf[String] -> "String", | |
classOf[Boolean] -> "Boolean", | |
classOf[Int] -> "Int" | |
) | |
val typeDefaults = Map[Class[_], String]( | |
classOf[String] -> "\"\"", | |
classOf[Boolean] -> "false", | |
classOf[Int] -> "0" | |
) | |
def renderType(c: Class[_]) = typeRenderings.getOrElse(c, c.getName) | |
def renderDefault(c: Class[_]) = typeDefaults.get(c).fold("")(" = " + _) | |
for (beanName <- args) { | |
val clazz = Class.forName(beanName) | |
val beanInfo = Introspector.getBeanInfo(clazz, classOf[Object]) | |
if(beanName == "com.zoho.books.model.TimeEntry") | |
beanInfo.getPropertyDescriptors.find(_.getName == "startTimer") | |
.foreach(_.setReadMethod(classOf[com.zoho.books.model.TimeEntry].getMethod("startTimer"))) | |
val caseClassName = clazz.getSimpleName | |
val javaName = clazz.getName | |
val props = beanInfo.getPropertyDescriptors.filter(p => p.getReadMethod != null && p.getWriteMethod != null) | |
val sb = new StringBuilder | |
sb ++= s"case class $caseClassName(\n" | |
for (p <- props) | |
sb ++= " " + p.getName + ": " + renderType(p.getPropertyType) + renderDefault(p.getPropertyType) + ",\n" | |
sb ++= | |
s""") { | |
| def toJava = { | |
| val obj = new $javaName | |
|${ | |
props | |
.map(p => " obj." + p.getWriteMethod.getName + "(" + p.getName + ")") | |
.mkString("\n") | |
} | |
| obj | |
| } | |
|} | |
|object $caseClassName { | |
| def fromJava(obj: $javaName): $caseClassName = | |
| $caseClassName( | |
|${ | |
props | |
.map(p => s" ${p.getName} = obj." + p.getReadMethod.getName + ",") | |
.mkString("\n") | |
} | |
| ) | |
|} | |
|""".stripMargin | |
val path = Paths.get(s"src/main/scala/$caseClassName.scala") | |
Files.createDirectories(path.getParent) | |
Files.writeString(path, sb) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment