4
當試圖通過字符串名稱獲取對象字段時,返回的值不是正確的scala類型。正如:如何根據字符串名稱和原始類型來獲取字段值的反射
import scala.language.reflectiveCalls
import scala.language.implicitConversions
case class Intity(flag: Boolean, id: Int, name: String)
val inty = Intity(false, 123, "blue")
implicit def reflect(r: AnyRef) = new {
def get(n:String) = {
val c = r.getClass.getDeclaredField(n)
c.setAccessible(true); c}
def getVal(n: String) = get(n).get(r)
def getType (n:String) = get(n).getType
}
然後使用這個
inty.getType("flag") // res0: Class[_] = boolean --not Boolean
inty.getVal("id") // res1: Object = 123 --Object not Int
做上述實施任何有效的方法是什麼時候?
而是反射,將[無形](https://github.com/milessabin/shapeless)就能解決問題了嗎? – Reactormonk
@Reactormonk但如何,我不知道多少倒黴到目前爲止。它是否支持通過其字符串名稱訪問類屬性,並通過原始類型返回值? – ALMEK
通過使用運行時反射,您永遠不會在編譯時獲得精確的類型。想想看。 –