简体   繁体   中英

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM