0

I'm developing a java program and my problem is that I want to write a general method for calling a specific method on a few classes, and the class is not known.

for example in normal use i write this piece of code for RootLayoutController class and it works:

RootLayoutController controller = loader.getController();
        controller.setMainApp(this)

but the problem is that i have to write a lot of methods to call them! so i created PageController interface ( with setMainApp() inside ) and implemented it in RootLayoutController and other classes ; then changed the method to this:

Object controller = loader.getController();
        ((PageController) controller).setMainApp(this);

but it throws classcastexception and I don't know much about interface so I can't debug it! thanks so much

3
  • 1
    Why are you getting back an object when you know you need something that implements the PageController interface? Commented Jan 9, 2015 at 20:15
  • It's pretty clear that loader.getController() is not returning a PageController. But you haven't told us what it does return, so I can't say any more than that. Commented Jan 9, 2015 at 20:16
  • it returns a class , it may be RootLayoutController or something else like PersonOverviewController! Commented Jan 9, 2015 at 20:19

2 Answers 2

1

If you have an interface PageController, you can do (because a RootLayoutController is a PageController.):

PageController controller = loader.getController();

and then, there is no necessity to cast:

controller.setMainApp(this);

This is why interfaces exist.

Sign up to request clarification or add additional context in comments.

2 Comments

That is, if getController isn't actually returning Object.
that works! thank you so much, I knew I had to use interface because all of those classes are doing the same action but I didn't know much about the syntax!
0

Under java 8, file PageController.java (interface):

package test;

@FunctionalInterface
public interface PageController {
    void setMainApp(PageController c);
}

File PageControllerImpl.java (test implementation):

package test;

public class PageControllerImpl implements PageController {

    @Override
    public void setMainApp(PageController c) {
        // TODO your implemenrtation

    }

    public static void main(String[] args) {
        PageController testController = new PageControllerImpl();
        testController.setMainApp(testController);        
    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.