I am trying to write an ExecutorService
as in Executors.newFixedThreadPool
with a runnable given as a parameter to method filling the ThreadPool
.
this is not about instantiating a inner class like proposed here How to instantiate inner class with reflection in Java? I actually want an alternative on using reflections.
The Runnable
to be run by the thread pool is an instance of an abstract runner. I can't create an instance with testRunnable.newInstance()
nor with testRunnable::new
because of an error caused by:
java.lang.NoSuchMethodException: ...$MyRunner.() exception.
For now I am doing this via reflections:
public void doStuff() throws Exception {
MyRunner r = new MyRunner();
for (int i = 0; i < 10; i++) {
doMoreStuff(r.getClass(), this);
}
}
public void doMoreStuff(Class<? extends TestRunner> clazz, Object... params) throws Exception {
Class<?>[] types = Stream.of(params).map(Object::getClass).toArray(n -> new Class[n]);
TestRunner t = clazz.getConstructor(types).newInstance(params);
new Thread(t).start();
}
Is there a better way to do this?