V
V
vyn2022-01-05 10:18:58
Java
vyn, 2022-01-05 10:18:58

How to correctly cast Class to an interface?

The Pizza class is read from the configuration and instantiated via Class.forName, it implements the IMeal interface. The question, in fact, is how to correctly cast the read Class to the IMeal interface?

private static IMeal readConfig() {
        Path dependencyPath = Paths.get("gof/src/main/java/resources/config.txt");

        File file = dependencyPath.toFile();
        IMeal IMeal = null;

        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String line = reader.readLine();
            Class mealClass = Class.forName(line);

            IMeal = IMeal.class.cast(mealClass);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }

        return IMeal;
    }

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question