javareflectionweld-se

Java reflection instance with Weld-SE context


I have a problem with creating object via reflection with Weld context.

I'm loading classes and their configuration from external files.

Simplify my code looks like:

final Class<?> moduleClass = Class.forName(properties.getProperty("className"));

then I'm creating instance of this class

final Constructor<?> constructor = moduleClass.getDeclaredConstructor();
module = (Module) constructor.newInstance();

Module class:

@ModuleImpl
public class ExampleModule extends AbstractModule (implements Module interface) {

    @Inject
    private Test test;

Module is created sucessfully, but it hasn't weld context to inject Test class. And I cannot find the correct way. I tried to make own producer but I'm not much familiar with Weld and CDI in Java SE yet.

My broken producer (I think that its totaly bad)

public class InjectionProvider {

    @Produces
    public Module getInsrance(Class<?> clazz) throws ReflectiveOperationException {
        final Constructor<?> constructor = clazz.getDeclaredConstructor();
        return (Module) constructor.newInstance();
    }
}

I cannot find something about this problem, so if anyone can help me I will be glad. I really need this way of creating classes because I don't want to change my code everytime when I need change some property in Module classes.

EDITED:

I cannot make it with producers. But I found a workaround. I'm not sure if is it good solution but it works for now.

I created a singleton class with Weld context.

public class TheMightyWeld {

    private static Weld weld;

    private static WeldContainer weldContainer;

    public static WeldContainer getThePowerOfCreation() {
        if (weldContainer == null) {
            weld = new Weld();
            weldContainer = weld.initialize();
        }
        return weldContainer;
    }

    public static void shutdown() {
        if (weld != null) {
            weld.shutdown();
        }
    }

}

And then I can initialize my app with

TheMightyWeld.getPowerOfCreation().instance().select(FXApplicationStarter.class).get().startApplication(primaryStage, getParameters());

And later in code I can reuse it for reflection

module = (Module) TheMightyWeld.getPowerOfCreation().instance().select(moduleClass).get();

EDITED 2:

I found better a solution. I can inject weld Instance

@Inject
private Instance<Object> creator;

then I can do only this

creator.select(moduleClass).get();

I think that this is a good solution.


Solution

  • See edited post. If someone have a better solution I will be glad for it.