import java.lang.reflect.Method;
public class ClazzReflectUtil {
public void runMethod(ClazzMethodInputDto inputDto) {
try {
Class<?> clazz = Class.forName(inputDto.getClazzName());
Method method = clazz.getMethod(inputDto.getClazzMethodName(), inputDto.getClazzMethodType());
method.invoke(clazz.newInstance(), inputDto.getClazzMethodValue());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
ClazzMethodInputDto inputDto = new ClazzMethodInputDto();
inputDto.setClazzName("com.syk.utils.clazzReflection.B");
inputDto.setClazzMethodName("doAdd");
inputDto.setClazzMethodType(Double.class);
inputDto.setClazzMethodValue(55.22);
new ClazzReflectUtil().runMethod(inputDto);
}
}
class A {
public void doAdd(String tips) {
System.out.println("=======doAddString==" + tips + "======");
}
public void doAdd(Double tips) {
System.out.println("=======doAddint==" + tips + "======");
}
public void doMinus(String tips) {
System.out.println("=======doMinus==" + tips + "======");
}
}
class B extends A {
public void doAdd(Double tips) {
System.out.println("=======BdoAddint==" + tips + "======");
}
}
package com.syk.utils.clazzReflection;
public class ClazzMethodInputDto {
/**
* 完整类名
*/
private String clazzName;
/**
* 类方法名
*/
private String clazzMethodName;
/**
* 类方法参数列表类型
*/
private Class<?> clazzMethodType;
/**
* 类方法参数列表值
*/
private Object clazzMethodValue;
public String getClazzName() {
return clazzName;
}
public void setClazzName(String clazzName) {
this.clazzName = clazzName;
}
public String getClazzMethodName() {
return clazzMethodName;
}
public void setClazzMethodName(String clazzMethodName) {
this.clazzMethodName = clazzMethodName;
}
public Class<?> getClazzMethodType() {
return clazzMethodType;
}
public void setClazzMethodType(Class<?> clazzMethodType) {
this.clazzMethodType = clazzMethodType;
}
public Object getClazzMethodValue() {
return clazzMethodValue;
}
public void setClazzMethodValue(Object clazzMethodValue) {
this.clazzMethodValue = clazzMethodValue;
}
}