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.

Need Your Help

IIS 6.0 not sending Expired header though I have turned it on

c# iis-6 windows-server-2003

My website is hosted on Windows server 2003, IIS 6.0. The website is developed on, with Microsoft Framework 3.5

Global sbteclipse plugin not found/loaded

scala plugins sbt sbteclipse

I am having some serious difficulty installing sbteclipse as a global plugin. It seams like the global plugins are not being loaded. I created the .sbt directory and added a plugins directory. I...