Instantiating class with dependency injection

Asked

Viewed 205 times

0

I have a method that calls other methods that are not predefined, I am using this library org.reflections and the method java.lang.reflect.Method#invoke to perform another method generically, that method(invoke) receives the first parameter with the instance of the class of the method I am going to execute and the other parameters are the args of the methods that will be executed, like this:

metodo.invoke(new InstanciaDaClasse(), args...);

The problem is, I’m running this invoke and passing as first parameter a new instance of a class that has an injected property, it has this:

@Inject
UsuarioController usuarioController;

The problem is that the q method I am running needs this usuarioController, but creating a new class instance with this @Inject this property is null, has some way to create a new instance of a class without losing the injections of dependencies in Runtime or make an injection of dependency "artificial"?

  • Why not pass the injected instance of the class you need to invoke?

  • @nullptr because I don’t know which class I’m going to instantiate, and I don’t know how to inject a class that I don’t know what it is, I’m making a generic method that executes other class methods that may have dependency injection

  • I’m not sure I understand the question, but according to what I understand why you need to pass the class of the method you are going to execute and its parameters? What is the reason for this?

  • @Gustavo the reason is that I need to run a generic method, so I found a way that’s the way I said it there in the question, what I explained in the question is how to run a method generically, and that’s right, it works, the problem is when this method is of a class that injects another class, because I need an instance of the class to be able to execute the method, understood?

  • What you can have is a map with all its classes injected, and in this your method pass the type of class desired instead of the instance, and search for the instance of this map.

  • In your class new InstanciaDaClasse() can have a constructor that receives the injected class. AI vc passes as parameter new InstanciaDaClasse(new ClasseInjetada()). I don’t know what the logic of your program is and there’s little code to be specific about. Maybe an option is to use the annotation @Qualifier tbm. Hard to say

  • @nullptr and Gustavo look at my class: https://github.com/brunoeas/poc-websocket-java/blob/master/src/main/java/br/com/poc_websocket_java/configuration/WebSocketConfiguration.java on line 119, the method invokeEventMethod calls another method "generically", I managed to solve the problem by making a method that makes an "injection of artificial dependencies", but I am not proud of this method no, it seems wrong, if you want to opinion, the will

Show 2 more comments

1 answer

0

I managed to solve the problem but not in the best possible way, I believe, so I will not consider the problem as solved.

A intenção was to perform a method generically, for that I use the method java.lang.reflect.Method#invoke library org.reflections, this method takes 2 or more parameters, the first is an instance of the class of the method I am going to execute, the second and the next parameters are considered parameters of the method I am going to execute, example:

metodoQueVaiSerExecutado.invoke(new ClasseDoMetodoQueVaiSerExecutado(), ...args);

O problema is that some classes have injection of dependencies, and just instantiating the class in this way would make their dependencies null.

A "solução" I created a method that instances the class, dependencies and dependencies of dependencies, in short that’s it:

/**
 * Injeta as dependências da classe e de todas suas dependências e retorna
 * uma nova instância da classe
 * 
 * @param classe - Classe que vai ser manipulada
 * @return Uma nova instância da classe passada por parâmetro
 * @throws Exception - Exception genérica
 */
private Object injectDependenciesAndReturnNewInstance(final Class<?> classe) throws Exception {

    final Object classToReturn = classe.newInstance();

    for (final Field field : classe.getDeclaredFields()) {
        if (!field.isAnnotationPresent(Inject.class)) {
            continue;
        }
        field.setAccessible(true);

        field.set(classToReturn, this.injectDependenciesAndReturnNewInstance(field.getType()));
    }

    return classToReturn;
}

So the method invoke was like this:

metodo.invoke(this.injectDependenciesAndReturnNewInstance(classe), ...args);

For more details you can ask me, and if help has the link of this class I’m doing in my repository: https://github.com/brunoeas/poc-websocket-java/blob/master/src/main/java/br/com/poc_websocket_java/configuration/WebSocketConfiguration.java

If anyone has any different ideas that can solve the problem they can send

Browser other questions tagged

You are not signed in. Login or sign up in order to post.