In Java, how can I load classes without knowing the name ahead of time?

52 views Asked by At

I have a directory that looks like this:

src
|
|__ProblemTester.java
|
|__problems
   |
   |__AbstractProblem.java
   |
   |__Problem1.java
   |
   |__Problem2.java
   |
   |__Problem3.java

All of the classes extend AbstractProblem. I want to have a function that takes the input int n and returns an instance of ProblemN.java (as part of a testing framework). Is this possible?

My code so far: (very rough)

class ProblemTester {

    Class<? extends AbstractProblem> problem;

    ProblemTest(int number) throws IllegalArgumentException {
        try {
            problem = Class.forName("problems.Problem" + number);
        } catch (ClassNotFoundException e) {
             throw new IllegalArgumentException(String.format("Problem %d not found.", number));
        }
    }

Unfortunately this throws the error Incompatible types. Required: Class<? extends AbstractProblem>. Found: Class<capture <?>>.

How can I fix this? Is there an existing framework for something like this? I've used gradle in the past but I don't think it loads classes automatically like I'd like this function to do. Thanks.

1

There are 1 answers

0
Nir Alfasi On BEST ANSWER

I might be wrong, but as far as I know Generics were not meant to be used as meta-types (for classes), so what you can do is, declare your problem as:

AbstractProblem problem;

and then:

Class clazz = Class.forName("Problem" + number);
problem = (AbstractProblem) clazz.newInstance();