Yvonne Chu
Yvonne Chu

Reputation: 65

Invoking method with name pattern

I need to call some functions generated by some libs. I will need to call fucntion1, function2, ..., function10 one by one. Instead of writing them all out on the code, is there any clever way to code it?

Upvotes: 2

Views: 117

Answers (2)

r0ast3d
r0ast3d

Reputation: 2637

You could also use the Expression class from java.beans package

http://download.oracle.com/javase/6/docs/api/index.html?java/beans/package-summary.html

construct a expression object.

Expression(Object target,String methodName,Object[] arguments)

and then on the expression object you can use getValue()

Cheers!

Upvotes: 1

BalusC
BalusC

Reputation: 1108702

You could use reflection.

Some some = new Some();

for (int i = 1; i <= 10; i++) {
    some.getClass().getMethod("function" + i).invoke(some);
}

Upvotes: 7

Related Questions