0

I want to know if we can do something like this in java. Say I have a class with some members:

Class Test {
  // some constructors and members
  public Object func;
} 

and then I have some functions defined from some other classes. I want to assign these functions to my Test class at runtime so that depending on the situation, eval(test.func) could be any function. How would you do that? It is rather easily done in javascript though, to pass around functions as string.

Is reflection or closure related to what I want to achieve? Thank you

user1589188
  • 5,316
  • 17
  • 67
  • 130

2 Answers2

1

You can use reflection to call the method by its name, e.g.

Method myMethod = getClass().getMethod("methodName",MyClass.class);
myMethod.invoke(classObj);

If you want something like eval to execute dynamic code, consider JRuby or Groovy

iTech
  • 18,192
  • 4
  • 57
  • 80
  • Yes something like eval could be handy but its not a must at this moment since my functions are properly defined at compile time. Thanks for mentioning Groovy, I will have a look later on :) – user1589188 Feb 12 '13 at 06:16
1

The answer is yes, you can do this, but should you? This pattern works great for languages with first-class functions, but java is the Kingdom of Nouns and different patterns apply.

When I absolutely have to do functional programming in Java, I use Google's Guava libraries to help. I could use reflections and stick with pure Java, but I like the abstractions Guava provides. Guava defines a Function object that is basically a reference to a function (with a generic input type and output type).

class Test {
  // some constructors and members
  public Function func;

  @Test
  public void testFunc() {
    assertEquals("abc", func.apply("123"));
  }
}
Cody A. Ray
  • 5,869
  • 1
  • 37
  • 31
  • Thank you for mentioning Guava! I dont need it at this point, but that could be something for me in the future. – user1589188 Feb 12 '13 at 06:15