//golang 通过反射创建实例
func main() {
var s Student
s.Name = "name1"
s.introduce() //把属性打印出来
ptr_s := reflect.ValueOf(&s)
ptr_s.Elem().FieldByName("Name").SetString("name1") //执行成功
s.introduce()
typeOf := reflect.TypeOf(s)
s2 := reflect.New(typeOf)
fmt.Println(reflect.TypeOf(s2).Name(), reflect.TypeOf(s2).Kind())
ptr_s2 := reflect.ValueOf(&s2)
ptr_s2.Elem().FieldByName("Name").SetString("name2") //执行失败
}
为什么s可以通过反射修改属性,s2无法修改?
反射创建的实例如何修改值?
refect.New 返回的就是一个
*Student
的Value
,不需要ptr_s2 := reflect.ValueOf(&s2)
了。s
类型是Student
,s2
并不是。s2
的类型是reflect.Value
,其值类型是*Student
,跟ptr_s
是一样的。所以,直接ptr_s2 := s2
就行。