Following method of BeanUtils parses a string based method signature.
public static Method resolveSignature(String signature, Class<?> clazz)
Where signature should be in the form 'methodName[([arg_list])]', arg_list is an optional, comma-separated list of fully-qualified type names, clazz is the target class containing the method to be resolved.
Examples
package com.logicbig.example;
import org.springframework.beans.BeanUtils;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ResolveSignature {
public static void main(String[] args) throws
InvocationTargetException, IllegalAccessException {
Method method = BeanUtils.resolveSignature("aMethod(java.lang.String, int)", LocalBean.class);
System.out.println("resolved method: " + method);
method.invoke(new LocalBean(), "some string value", 100);
method = BeanUtils.resolveSignature("aMethod(java.lang.Integer)", LocalBean.class);
System.out.println("resolved method: " + method);
method.invoke(new LocalBean(), 200);
}
private static class LocalBean {
public void aMethod(String str, int anInt) {
System.out.printf("aMethod invoked with params, str: %s, anInt: %s%n", str, anInt);
}
public void aMethod(Integer anInt) {
System.out.printf("aMethod invoked with param, anInt: %s%n", anInt);
}
}
}
Outputresolved method: public void com.logicbig.example.ResolveSignature$LocalBean.aMethod(java.lang.String,int) aMethod invoked with params, str: some string value, anInt: 100 resolved method: public void com.logicbig.example.ResolveSignature$LocalBean.aMethod(java.lang.Integer) aMethod invoked with param, anInt: 200
package com.logicbig.example;
import org.springframework.beans.BeanUtils;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ResolveSignature2 {
public static void main(String[] args) throws
InvocationTargetException, IllegalAccessException {
Method method = BeanUtils.resolveSignature("doSomething", LocalBean.class);
System.out.println("resolved method: "+method);
method.invoke(new LocalBean());
}
private static class LocalBean {
public void doSomething() {
System.out.println("-- doing something -- ");
}
}
}
Outputresolved method: public void com.logicbig.example.ResolveSignature2$LocalBean.doSomething() -- doing something --
Example ProjectDependencies and Technologies Used: - spring-context 6.1.2 (Spring Context)
Version Compatibility: 3.2.3.RELEASE - 6.1.2 Version compatibilities of spring-context with this example: Versions in green have been tested.
- JDK 17
- Maven 3.8.1
|