Search code examples
javagenericscastingextendsunchecked-cast

Java: Generic type casting, how can I fix this so I don't suppress the unchecked warning


private static transient JavaPlugin myPlugin = null;

public SomeClass(JavaPlugin plugin) {
    if (myPlugin == null) myPlugin = plugin;
}

public <T> T getPlugin(Class<? extends JavaPlugin> plugin) {
    return (T)myPlugin; // return casted version of "myPlugin" form above
}

Calling it in the line below works just fine, and trying to use a class that doesn't extend JavaPlugin will throw a compile time error. But how can I make it so the above function works without requiring @SuppressWarnings("unchecked")??

MyPlugin nc = this.getPlugin(my.main.package.MyPlugin.class);

Solution

  • You are aware that you are actually returning a Class instance from your method, and storing it in a reference of type MyPlugin? So, you are actually assigning Class<MyPlugin> instance to MyPlugin. that is not going to work.

    To workaround with that, you have to use Class#newInstance() method to return an instance of that class you are passing. And make the parameter type Class<T>:

    public <T extends MyPlugin> T getPlugin(Class<T> plugin) {
        return plugin.newInstance();
    }
    

    Well, I've just given you an idea of what you were doing wrong. You have to handle appropriate exceptions, and also check if the class you are passing has a 0-arg constructor, else it won't work.