svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.library / org.gvsig.expressionevaluator / org.gvsig.expressionevaluator.lib / org.gvsig.expressionevaluator.lib.impl / src / main / java / org / gvsig / expressionevaluator / impl / InstanceUtils.java @ 46901
History | View | Annotate | Download (2.02 KB)
1 |
package org.gvsig.expressionevaluator.impl; |
---|---|
2 |
|
3 |
import java.lang.reflect.Method; |
4 |
import org.apache.commons.lang3.StringUtils; |
5 |
|
6 |
|
7 |
/**
|
8 |
*
|
9 |
* @author jjdelcerro
|
10 |
*/
|
11 |
public class InstanceUtils { |
12 |
|
13 |
public static Object callmethod(Object instance, String methodName, Object args[]) throws Exception { |
14 |
if( StringUtils.isBlank(methodName) ) {
|
15 |
throw new NullPointerException("A method name was expected to invoke and a null was received"); |
16 |
} |
17 |
if( instance==null ) { |
18 |
throw new NullPointerException("An object pointer was expected to invoke method "+methodName+" and a null was received"); |
19 |
} |
20 |
Class[] parameterTypes = new Class[args.length]; |
21 |
Object[] parameters = new Object[args.length]; |
22 |
for (int i = 0; i < parameters.length; i++) { |
23 |
Object parameter = args[i];
|
24 |
parameters[i] = parameter; |
25 |
if( parameter==null ) { |
26 |
parameterTypes[i] = null;
|
27 |
} else {
|
28 |
parameterTypes[i] = parameter.getClass(); |
29 |
} |
30 |
} |
31 |
Class<?> theClass = instance.getClass();
|
32 |
Method method;
|
33 |
try {
|
34 |
method = theClass.getMethod(methodName, parameterTypes); |
35 |
} catch(NoSuchMethodException ex) { |
36 |
// Esto es para esquivar casos como tener un ArrayList de objects y
|
37 |
// hacer algo como arr.add(10). Dice que no hay ningun metodo add
|
38 |
// que reciba un Integer, por que realmente el add esta declarado como
|
39 |
// que recibe un object.
|
40 |
// Ver TestInterpreter metodo testListAppend.
|
41 |
for (Method m : theClass.getMethods()) { |
42 |
if( StringUtils.equals(m.getName(), methodName) && parameterTypes.length == m.getParameterTypes().length) {
|
43 |
parameterTypes = m.getParameterTypes(); |
44 |
break;
|
45 |
} |
46 |
} |
47 |
method = theClass.getMethod(methodName, parameterTypes); |
48 |
} |
49 |
Object value = method.invoke(instance, parameters);
|
50 |
return value;
|
51 |
} |
52 |
|
53 |
} |