Getting public fields (and their respective values) of an Instance in Scala/Java

前端 未结 5 949
耶瑟儿~
耶瑟儿~ 2020-12-20 14:13

PHP introduces a method that allows you to pick out all public values of an instance. Is there any way to do this in Scala? That is to fetch all values of all public fields

5条回答
  •  再見小時候
    2020-12-20 14:48

    Just a note to those who try to improve this by making @duncan 's approach type-stronger:

    Instead of returning a Map[String, Any], where the value is typed as Any, you could do following:

    def propertiesAsPairs() = {
        val fields = (this.getClass.getDeclaredFields())
        for ( field <- fields ) yield {
            field.setAccessible( true );
            ( field.getName, field.get( this ) );
        }
    }
    

提交回复
热议问题