Golang Simple Reflection

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.
package testfuncimport("fmt")type Test struct{Name stringAge int}/*type Intio interface {Stringtest() string}*/func (this Test) Stringtest(){fmt.Println(this.Name)}func (this Test) Stringtest2(){fmt.Println("Stringtest2",this.Name)}func (this *Test) Stringtest1(i int){this.Age=ifmt.Println(this.Age)}func GetNumArgs(args []string,num int) string{if num==0 {num=1}return args[num]}

package mainimport("testfunc""reflect""fmt")func main(){d:=&testfunc.Test{"lyl",18}v:=reflect.ValueOf(d)ele:=v.Elem()t:=ele.Type()//读取这个对象的所有属性fmt.Println("读取这个对象的所有属性")for i:=0;i<t.NumField();i++{fmt.Println(t.Field(i).Name,ele.Field(i).Interface())}//读取对象方法fmt.Println("读取所有对象的方法")for i := 0; i < t.NumMethod(); i++ {fmt.Println(t.Method(i).Name)}fmt.Println("函数调用测试")ele.MethodByName("Stringtest").Call(nil)fmt.Println("带参函数调用")//func (this *Test) 需要指针调用fmt.Println("未修改的年龄",d.Age)iage:=reflect.ValueOf(11)v.MethodByName("Stringtest1").Call([]reflect.Value{iage})//参数转换成reflect.Valuefmt.Println("反射调用通过指针修改后的年龄",d.Age)}

Unable to traverse out pointer method

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.