In PHP (for example), you can use this way to call a function using a variable like this:

$funcname = "print";
$funcname("Whatever..."); // Same as: print("Whatever...");

What is the way used in Java?

8 Answers

15
akuhn On Best Solutions

You can use

Class<?> klass = object.getClass();
Method method = klass.getMethod("name", String.class); // parameter types, if any
method.invoke(object, "whatever"); // parameters, if any 

plus boilerplate code to catch 5 different exception (they promised to introduce a common supertype in Java 7).

2
Björn On

Java Reflection API can provide this functionality. (Not exactly as PHP does it, thou)

6
Yacoby On

Yes. Use Method.invoke. Also there is some examples here

1
Peter Lang On

You could use reflection, but if you want to have a method that prints something, and you want to change that behavior later, just write a method and call that.

7
T.J. Crowder On

Although you can do this with reflection as many have indicated, for the use case you mention in your comment responding to the comment asking "why?", I'd use an interface instead.

17
Dave Sims On

Please keep in mind that reflection of this kind is not typical in Java the way it is in more functionally-oriented languages like Ruby or even (wait for it) C#. There's nothing wrong with the technique per se, but you do lose compiler protection which may result in difficult-to-find bugs or confusing code for other devs who don't anticipate these kinds of paths. I'm not one that thinks all reflection in Java is considered harmful, but it's definitely not mainstream practice. Use with caution.

Perhaps a better and more Java-friendly solution would be to use a Command Pattern. Create an array of functional-like objects with an "execute" method that performs the various operations you want. Use an Interface to abstract.

public interface Command {
    public void execute();
}

public class Foo implements Command{
    public void execute() {
        // do some stuff 
    }
}

You can implement Command in a concrete class or anonymous inner class and iterate over an array of Commands:

List<Command> commandArray = new <Command>ArrayList();
commandArray.add(new Foo());
commandArray.add(new Command(){
    public void execute() {
        // some more stuff;
    }
});

for (Command command : commandArray){
    command.execute();
}

EDIT: per Adrian's comment, here's a way to call a method/command from a variable iterating over an array of values:

public interface StringCommand {
    public void execute(String value);
}

stringCommand = new StringCommand(){
    public void execute(String value){
        System.out.println(value.toLowerCase());
    }
}

String[] stringAry = {"foo", "fu", "Whatever..."};

for(String value : stringAry){
    stringCommand.execute(value);
}

Would be similar in Ruby to:

string_command = lambda {|value| puts value.downcase }
["foo", "fu", "Whatever..."].each { |value| string_command.call(value)}
0
fastcodejava On

You can use reflection as others have suggested. Syntactically it is quite different from what you expected.

0
kuaw26 On

Next version of JDK - JDK7 would probably have closures support. If you don't want to wait for official release in Fall 2011 you can try betta versions already. google for Java/JDK 7.