lundi 25 mai 2020

How to dynamically add ByteBuddy-generated class as a spring bean

I am making my own ORM as a reflection / generics exercise. What I am trying to do is to create classes extending my AbstractDao class with ByteBuddy and register them as beans. The following code throws the following error (note that the c variable is obtained by looping through Spring beans flagged with a certain annotation):

Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)

var daoClass = byteBuddy
                    .subclass(TypeDescription.Generic.Builder.parameterizedType(AbstractDao.class, c.getClass(), Long.class).build())
                    .annotateType(AnnotationDescription.Builder.ofType(Repository.class).build())
                    .make();

                var clazz = daoClass.load(getClass().getClassLoader()).getLoaded();

                ((GenericApplicationContext) context).registerBean(clazz, clazz.getConstructor().newInstance());

Sounds like it's not finding a no-args constructor. I tried adding one and now it's complaining about a duplicate method signature (!) :

var daoClass = byteBuddy
                    .subclass(TypeDescription.Generic.Builder.parameterizedType(AbstractDao.class, c.getClass(), Long.class).build())
                    .annotateType(AnnotationDescription.Builder.ofType(Repository.class).build())
                    .defineConstructor(Visibility.PUBLIC)
                        .intercept(MethodCall.invoke(Object.class.getConstructor()))
                    .make();

                var clazz = daoClass.load(getClass().getClassLoader()).getLoaded();

                ((GenericApplicationContext) context).registerBean(clazz, clazz.getConstructor().newInstance());

What am I doing wrong?





Aucun commentaire:

Enregistrer un commentaire