Reputation: 43
I am trying to do something like this....
public class myClass2 extends myClass1
{
@Override
public void printStuff() { }
}
public class dostuff
{
public dostuff()
{
doSomething(myClass2.Class());
}
public void doSomething(Class<myClass1> cls)
{
cls.printStuff();
}
}
Im getting compile errors like this
Required: myClass1 Found: myClass2
How can I tell the function to except subclasses of myClass1?
Upvotes: 0
Views: 46
Reputation: 393811
public void doSomething(Class<? extends myClass1> cls)
{
try {
cls.newInstance().printStuff();
} catch (InstantiationException e) {
....
} catch (IllegalAccessException e) {
....
}
}
To let the method expect sub-classes of myClass1
, you have to use a bounded type parameter.
You have to create an instance of the class in order to call the method printStuff()
.
You also have an error in dostuff
. It should be :
public void dostuff()
{
doSomething(myClass2.class);
}
Upvotes: 1