2018-04-03 09:02:31 +00:00
|
|
|
package annotation
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"reflect"
|
|
|
|
|
|
|
|
cur "git.loafle.net/commons/util-go/reflect"
|
|
|
|
)
|
|
|
|
|
|
|
|
var annotationRegistry map[string]*AnnotationDefinition
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
annotationRegistry = make(map[string]*AnnotationDefinition, 0)
|
|
|
|
}
|
|
|
|
|
2018-04-06 16:57:25 +00:00
|
|
|
func RegisterAnnotation(t reflect.Type) error {
|
|
|
|
rt, _, _ := cur.GetTypeInfo(t)
|
|
|
|
|
|
|
|
f := getTypeAnnotationField(t)
|
|
|
|
if nil == f {
|
|
|
|
return fmt.Errorf("DI: This type[%s] is not Annotation", rt.Name())
|
|
|
|
}
|
|
|
|
|
|
|
|
name, _ := parseAnnotationMeta(f.Tag)
|
|
|
|
|
2018-04-03 09:02:31 +00:00
|
|
|
if _, ok := annotationRegistry[name]; ok {
|
|
|
|
return fmt.Errorf("DI: name[%s] of annotation exist already", name)
|
|
|
|
}
|
|
|
|
|
|
|
|
meta := getMetaFields(t)
|
|
|
|
|
|
|
|
def := &AnnotationDefinition{
|
|
|
|
t: t,
|
2018-04-06 16:57:25 +00:00
|
|
|
rt: rt,
|
2018-04-03 09:02:31 +00:00
|
|
|
fields: meta,
|
|
|
|
}
|
|
|
|
|
|
|
|
annotationRegistry[name] = def
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
type AnnotationDefinition struct {
|
|
|
|
t reflect.Type
|
|
|
|
rt reflect.Type
|
|
|
|
|
|
|
|
fields map[string]*AnnotationFieldMeta
|
|
|
|
}
|
2018-04-06 16:57:25 +00:00
|
|
|
|
|
|
|
func getTypeAnnotationField(t reflect.Type) *reflect.StructField {
|
|
|
|
rt, _, _ := cur.GetTypeInfo(t)
|
|
|
|
if reflect.Struct != rt.Kind() {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
for i := 0; i < rt.NumField(); i++ {
|
|
|
|
f := rt.Field(i)
|
|
|
|
|
|
|
|
if f.Anonymous {
|
|
|
|
if f.Type == TypeAnnotationType {
|
|
|
|
return &f
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|