Search code examples
javagenericsinheritancesubclasssuperclass

using a method that is only defined in the subclasses - JAVA


I am trying to implement a plugin for a java project where I only have access to the interfaces.
The project has following structure:

superclass: A
subclasses: B, C, E and F

All the subclasses B, C, D, E and F extend the class A and have a method called "execute()". This method is not defined in the superclass(A).

Now I want to implement a method in my plugin called "doSomething()" that uses the "execute()" method of the subclasses B, C, D, E and F.
And I don't want to duplicate the same method 4 times (for each subclass).

When I put the superclass (A) as parameter, I cannot access to the method defined in the subclasses:

public void doSomething(A a) {
   a.execute()
}

I also tried to generify the doSomething() method and define multiple upper bounds like this:

public <T extends B, C, D, E, F> void doSomething(T t) {
   t.execute();
}

But it is not possible to define more than one class in the upper bounds, since it's not possible to have types, which inherit from more than one super-class.

Is there any way to implement the doSomething() method without duplicating it or changing the source code of the subclasses?
Please note that I cannot change any of the given classes (A, ... F).


Solution

  • probably somehow like that:

    public static void doSomething(Object object) {
            try {
                Method method = object.getClass().getDeclaredMethod("execute", null);
                method.invoke(object);
            } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    
    A b = new B();
    doSomething(b);