reified type paramter = å ·è±¡åãããåãã©ã¡ã¼ã¿
ååãå¼·ããã
ç®çã¨ãã¦ã¯Kotlinã§Javaã¯ã©ã¹(Class
ã¤ã³ã¹ã¿ã³ã¹)ãå¾ãããã®é¢æ°javaClass
ããã£ã¨æ¥½ã«ä½¿ããããã«ãããã¨ã£ã½ãã
ä¾ãã°ä»ã¾ã§ã¯ãããããé¢æ°âãä½ãã«ã¯å¼æ°ã¨ãã¦Class
ã¤ã³ã¹ã¿ã³ã¹ãåãåãå¿
è¦ããã£ãã
fun getName(clazz: Class<*>): String = clazz.getSimpleName()
ã¾ã¼ããããããªãå¥ã«ãããã ãã©ãããã使ãå´ãã¡ãã£ã¨ããã«ãªãã
val name = getName(javaClass<StringBuffer>()) println(name) // => StringBuffer
getName(javaClass<StringBuffer>())
ã£ã¦ã®ãããµãã
getName<StringBuffer>()
ã¨ããã³ã¼ããæ¸ãããã¤ã«ãã
ã¨ãããã¨ã§reified type parameterããããå®ç¾ãã¦ãããï¼
ãããªæãã§ä½¿ãã¾ãã
inline fun getName<reified T>(): String = javaClass<T>().getSimpleName()
åå¤æ°ã®å®£è¨ã®ã¨ããã«reified
ã¨ãããã¼ã¯ã¼ããç½®ãã
ããã«reified
ãããé¢æ°ã¯å¿
ãinline
æå®ããªããã°ãªããªãã
val name = getName<StringBuffer>() println(name) // => StringBuffer
ããã便å©ã ï¼
Class
ã使ãå ´é¢ã£ã¦æ®æ®µã¯ãã¾ããªããã©ãã¬ã¼ã ã¯ã¼ã¯ã¨ãä½ã£ã¦ãã¨ä½¿ããããªããã¨ãå¤ãã
以åã¡ããã£ã¨ã ãä½ã£ãKotlinã§DIãã¦ããããã¤ã«ããã®reified type parameterã®ä»çµã¿ãåãå ¥ããã
ä»ã¾ã§injector.getInstance(javaClass<HelloWorld>())
ã¨æ¸ãã¦ããã®ãinjector.getInstance<HelloWorld>()
ã£ã¦æ¸ããã®æ¬å½ãããããã