clankill3r
clankill3r

Reputation: 9543

check if a class contains a method

I have a abstract class to create tools (like illustrator pen, selection etc). The idea is that users can create easily new tools if they like.

Some tools have a method called, "draggingSelection". I wonder if there is a way to check if a class has that object, and if so, run it. (In this case draggingSelection returns a boolean)

So far i can figure out if the method exists or not. I only can't get it the method to run. I tried things with invoke but i fail at it. My method doesn't requite any parameters. Could somone help.

public boolean draggingSelection() {

    Method[] meths = activeTool.getClass().getMethods();
    for (int i = 0; i < meths.length; i++) {
        if (meths[i].getName().equals("draggingSelection")) {
            // how can i run it?
                        //return meths[i].draggingSelection(); // wrong     
        }
    }
    return false;

}

Upvotes: 1

Views: 1013

Answers (3)

tckmn
tckmn

Reputation: 59293

public interface Draggable {
    public boolean draggingSelection(int foo, int bar);
}

Then when you have a class with this method just add implements Draggable. Example:

public class Selection implements Draggable {
    public boolean draggingSelection(int foo, int bar) {
        (insert code here)
        return baz;
    }
    (insert rest of code here)
}

Therefore your example would be:

if (activeTool instanceof Draggable) {
    ((Draggable)activeTool).draggingSelection(foo, bar);
}

Upvotes: 1

Joachim Sauer
Joachim Sauer

Reputation: 308101

You could do that via reflection, but a far better solution would be to have an interface that has all the relevant methods:

public interface SelectionAware {
  public void draggingSelection(SelectionEvent e);
}

Once you have that, you have (at least) two options to use it:

  1. let your tools implement that interface and use myTool instanceof SelectionAware followed by a cast to call that method or
  2. let the tool explicitly register itself as a listener in some appropriate init method.

Option 1 is closer to what you attempted to do, but restricts the use of that interface and is not really clean code (because your code needs to "guess" if some tool implements some interface).

Option 2 is probably slightly more work (where/when to register/unregister the listener? ...), but is definitely the cleaner approach. It also has the advantage that the listeners are not restricted to being tools: anything could register such a listener.

Upvotes: 2

hsz
hsz

Reputation: 152256

Better solution in my opinion is to check if given object's class implements some interface.

However, to call draggingSelection method, do it on an object that you are testing:

activeTool.draggingSelection()

Upvotes: 2

Related Questions