mercredi 30 septembre 2020

How to create instance by interface using reflection?

I'm trying coding Spring's DI , just a simple example. There is a controller, and this @AutoWired is a Empty Annotation defined by me.

public class UserController {
    @AutoWired
    private UserServise userServise;
}

This is the code that implement Annotation injection:

UserController userController = new UserController();
Class<? extends UserController> clazz = userController.getClass();

Stream.of(clazz.getDeclaredFields()).forEach(field -> {
    AutoWired annotation = field.getAnnotation(AutoWired.class);
    if (annotation != null) {
        field.setAccessible(true);
        Class<?> type = field.getType();
        try {
            Object o = type.getDeclaredConstructor().newInstance();
            field.set(userController, o);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
});

When the program runs into

Object o = type.getDeclaredConstructor().newInstance();

throws

java.lang.NoSuchMethodException: com.learning.servise.UserServise.<init>()

I guess program cannot find a constructor for a interface, So how can I create this instance for the injection?





Aucun commentaire:

Enregistrer un commentaire