reflect.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package mhayaReflect
  2. import (
  3. "fmt"
  4. "reflect"
  5. "runtime"
  6. cstring "github.com/mhaya/extend/string"
  7. )
  8. func ReflectTry(f reflect.Value, args []reflect.Value, handler func(interface{})) {
  9. defer func() {
  10. if err := recover(); err != nil {
  11. fmt.Println("-------------panic recover---------------")
  12. if handler != nil {
  13. handler(err)
  14. }
  15. }
  16. }()
  17. f.Call(args)
  18. }
  19. func GetStructName(v interface{}) string {
  20. return reflect.Indirect(reflect.ValueOf(v)).Type().Name()
  21. }
  22. func GetFuncName(fn interface{}) string {
  23. if reflect.TypeOf(fn).Kind() != reflect.Func {
  24. panic(fmt.Sprintf("[fn = %v] is not func type.", fn))
  25. }
  26. fullName := runtime.FuncForPC(reflect.ValueOf(fn).Pointer()).Name()
  27. return cstring.CutLastString(fullName, ".", "-")
  28. }
  29. ////GetInvokeFunc reflect function convert to MethodInfo
  30. //func GetInvokeFunc(name string, fn interface{}) (*cfacade.MethodInfo, error) {
  31. // if name == "" {
  32. // return nil, cerr.Error("func name is nil")
  33. // }
  34. //
  35. // if fn == nil {
  36. // return nil, cerr.Errorf("func is nil. name = %s", name)
  37. // }
  38. //
  39. // typ := reflect.TypeOf(fn)
  40. // val := reflect.ValueOf(fn)
  41. //
  42. // if typ.Kind() != reflect.Func {
  43. // return nil, cerr.Errorf("name = %s is not func type.", name)
  44. // }
  45. //
  46. // var inArgs []reflect.Type
  47. // for i := 0; i < typ.NumIn(); i++ {
  48. // t := typ.In(i)
  49. // inArgs = append(inArgs, t)
  50. // }
  51. //
  52. // var outArgs []reflect.Type
  53. // for i := 0; i < typ.NumOut(); i++ {
  54. // t := typ.Out(i)
  55. // outArgs = append(outArgs, t)
  56. // }
  57. //
  58. // invoke := &cfacade.MethodInfo{
  59. // Type: typ,
  60. // Value: val,
  61. // InArgs: inArgs,
  62. // OutArgs: outArgs,
  63. // }
  64. //
  65. // return invoke, nil
  66. //}
  67. func IsPtr(val interface{}) bool {
  68. if val == nil {
  69. return false
  70. }
  71. return reflect.TypeOf(val).Kind() == reflect.Ptr
  72. }
  73. func IsNotPtr(val interface{}) bool {
  74. if val == nil {
  75. return false
  76. }
  77. return reflect.TypeOf(val).Kind() != reflect.Ptr
  78. }