Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question