1
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);
Nahydrin
  • 13,197
  • 12
  • 59
  • 101

1 Answers1

6

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.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • Sorry I seem to have left out something crucial. I will not know that "MyPlugin" exists, I need to cast my class level variable `myPlugin` of type `JavaPlugin` to the type `Class plugin`. – Nahydrin Jan 10 '14 at 15:58
  • @BrianGraham You mean to say, you want to perform down-casting here? Look out for `Class.cast` method. – Rohit Jain Jan 10 '14 at 16:01
  • Thanks, figured it out now. I'll accept this as answering both of my questions. :) – Nahydrin Jan 10 '14 at 16:05