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 typeMyPlugin
? So, you are actually assigningClass<MyPlugin>
instance toMyPlugin
. 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 typeClass<T>
: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.