0

I'm trying to achieve to get a class from his name. In my case all classes I want to get implements the generic interface Prototype<T>.

But the delicate part of my problem is that I'm "Warningophobe".

I wrote:

// Warning: Usage of interface raw type
Class<? extends Prototype> prototypeClass;
try {
    Class<?> clazz = Class.forName("mova.game.monster.Goblin");
    prototypeClass = clazz.asSubclass(Prototype.class);
    System.out.println(prototypeClass);
} catch (ClassNotFoundException cnfe) {
    cnfe.printStackTrace();
}

This code work, but here, my IDE (IntellIJ) tell me that I'm using my "raw interface".

I know I can do that:

Class<? extends Prototype<?>> prototypeClass;
try {
    Class<?> clazz = Class.forName("mova.game.monster.Goblin");
    // Warning: unchecked cast
    prototypeClass = (Class<? extends Prototype<?>>) clazz.asSubclass(Prototype.class);
    System.out.println(prototypeClass);
} catch (ClassNotFoundException cnfe) {
    cnfe.printStackTrace();
}

But now, I have an uncheked cast.

So, is there a proper way to achieve this problem without warning?

Mohicane
  • 302
  • 2
  • 15
  • See https://stackoverflow.com/questions/2390662/java-how-do-i-get-a-class-literal-from-a-generic-type Just suppress the unchecked cast warning. – Sweeper Jun 22 '21 at 10:11
  • I've allready tried but it leads to a compilation error: Required Type: Class extends Prototype>> Provided Type: Class – Mohicane Jun 22 '21 at 10:17
  • Do you need to obtain the class from a String name? If there are a limited number of classes implementing Prototype, you can use a different representation, like an enum, and map each constant to a factory method. If you might be dealing with third party code that declares its own Prototype implementations, you may want to use [ServiceLoader](https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/util/ServiceLoader.html). – VGR Jun 22 '21 at 15:07
  • I have to instantiate hundred of objects from json models in a file. These models could contain a class name. So I have to retreive the class. These parts work. The only problems are the warning when I want to subclass as Prototype. – Mohicane Jun 23 '21 at 06:14

0 Answers0