1

If you have a list of class names in a list such as

List<String> runnables = null;
runnables.add("runnable1");
runnables.add("runnable2");
runnables.add("runnable3");

Each of the classes implements Runnable

So for example, this works

Thread t1 = new Thread(new runnable1());
t1.start(); 

However, what if you want to loop through and run all of them from the array and the array is built dynamically at run time. i.e. you don't know at the time of coding what class names will be in the list as they can change.

runnables.forEach((String classname) -> {
    System.out.println("The runnable is " + (String) classname);
    Thread t1 = new Thread(new classname()); 
    t1.start();       
});

Doesn't work, it says " cannot find symbol symbol: class classname location: class ConncurrencyTesting " On the line that starts "Thread t1 = ...." in the forEach.

1
  • For the record: reflection is somehow a complete "topic" on its own. If you really know nothing about that; I see a certain chance that you are overburdening yourself. Commented Jun 21, 2017 at 10:38

1 Answer 1

3

If the class is loaded prior to attempting to utilize it, you can replace this line:

Thread t1 = new Thread(new classname());

With this line that uses reflection to generate an instance from the class name:

Thread t1 = new Thread((Runnable)Class.forName(className).newInstance());

The trick is, the classes must all implement Runnable and the String class name must also include the package directory as well. (e.g. instead of "Triangle" it would need to be "shape.Triangle"

However, if you are trying to use a class that is outside of the classpath, you will need to use a ClassLoader to load the class before trying to instantiate it. I don't recommend this as it is a higher level concept and will cause a large headache if you are not well versed in the way that Java handles loading of classes.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.