Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - method selectors?

Tags:

java

I'm coming from an Objective-C background. In Objective-C, you can store references to methods by using @selector variables, for example @selector(terminate). Then, you can simply "apply" those selectors on objects, which executes the method described by the selector.

Now, I have to program something in Java. Is there anything similar to this in Java? Or a workaround?

EDIT: Basically, I'm creating a CLI program. When I read in the commands, I have to map the commands to certain methods. I thought about creating a dictionary associating a command with a method selector.

like image 519
ryyst Avatar asked Jun 02 '26 18:06

ryyst


1 Answers

Nothing nice. The only method to enable you to do a similar thing is reflection:

public class ReflectionExample {
    private static class A {
        public void foo() {
            System.out.println("fooing A now");
        }
    }

    public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException,
            IllegalAccessException, InvocationTargetException {
        Method method = A.class.getMethod("foo");
        method.invoke(new A());
    }
}

And then you can only call Method.invoke on an object of the same class (or a subclass).

EDIT: To solve your exact problem I think you are probably best creating one class for each command. Each of these classes can implement an interface that will contain the method to perform the command and probably also a String getter for the name of the command. You can then populate a collection with command instances.

The only danger of this method is you add a new command class and forget to create an instance of it. The best method I have found to avoid that is to use an enumeration with one member for each command. To create the instances you can iterate over the enumerations values and use a switch case to create the instances. Some IDEs (such as Eclipse) can generate a warning or error if an enumeration instance is not covered in a switch - that will tell you immediately if you have forgotten to create a command instance.

like image 180
Russ Hayward Avatar answered Jun 04 '26 08:06

Russ Hayward



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!