Stephan van Hulst wrote:Why do you have a list of Class? Why not just a list of Runnable?
Luigi Plinge wrote:I was thinking of testing before I instantiate the object, but I can't see how to do that.
Stephan van Hulst wrote:I'm curious though, why would you want to do this? What is the purpose of your code?
Keep in mind that your code is very dangerous. Anyone could just drop a class file in that package and your code would run it and it would potentially wreak havoc.
Matthew Brown wrote:One other thing to consider - is there any chance that any of your classes don't have a no-arg constructor? If so you'll get an exception when you use Class.newInstance(), so you'll have to cope with that possibility.
[Edit: and what Stephan said ]
Matthew Brown wrote:
Or, if you want to check before you create the object, have a look at the isAssignableFrom method of Class.
public boolean isAssignableFrom(Class<?> cls)
Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter. It returns true if so; otherwise it returns false. If this Class object represents a primitive type, this method returns true if the specified Class parameter is exactly this Class object; otherwise it returns false.
Specifically, this method tests whether the type represented by the specified Class parameter can be converted to the type represented by this Class object via an identity conversion or via a widening reference conversion. See The Java Language Specification, sections 5.1.1 and 5.1.4 , for details.
Stephan van Hulst wrote:Yes, you need to pass your Class instances to the isAssignableFrom method.
However, isAssignableFrom is not a method in Runnable. So you don't need a Runnable instance. What kind of instance do you need?