Search code examples
javaclassinheritanceparameterssubclassing

java referencing Class<> as their subtype


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?


Solution

  • public void doSomething(Class<? extends myClass1> cls) 
    {
        try {
          cls.newInstance().printStuff();
        } catch (InstantiationException e) {
          ....
        } catch (IllegalAccessException e) {
          ....
        }
    }
    
    1. To let the method expect sub-classes of myClass1, you have to use a bounded type parameter.

    2. 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);
       }