我只是使用方法反射API创建一个通用方法。在这种方法中,我试图获得一个微粒方法(getter方法/setter方法)值,但我被卡住了,我不知道如何做到这一点。我是Abel使用方法反射API获得所有方法名称,但不是Abel获得该方法的值。所以请帮帮我。
这是我的代码......
/*
propertyNames List包含两条记录
and that records are two different EntityName(Variable Name)
ex. in my class i have declared two Entity(Variable)
private Integer productId;
private Integer bomBucket;
so propertyNames List is contain [productId , bomBucket] this two records.
*/
public <T>void fillList(List<String> propertyNames , T clas){
try{
for(Object entity : entities.keySet()){
if(propertyNames != null && propertyNames.size() > 0){
Method[] methodList = clas.getClass().getMethods();
Method methodName;
for (String propertyName : propertyNames) {
for(Method method : methodList){
if(method.getName().trim().startsWith("set")){
if(propertyName.trim().equalsIgnoreCase(method.getName().substring(3, method.getName().trim().length()))){
methodName = clas.getClass().getMethod(method.getName().trim(),new Class[]{Integer.class});
System.out.println("HERE I GET METHOD NAME ::: " + methodName.getName());
/*
* here one by one i am getting all the Setter methods name from the class .
* but i want a that Setter methods values. Not return type.
*/
}
}
}
}
}
}
}catch (Exception e) {
e.printStackTrace();
}
}
你的意思是"方法的值"你是指方法的返回类型,还是你想调用那个方法,在它的父类的某个实例上,也许有一些参数,然后得到它返回的值?在这种情况下,如果你的方法不是公共的,你必须在调用方法对象之前先调用setAccessible(true):
//get instance of the class that has your method
DsrProcessor dsrProcessor = DsrProcessor.class.newInstance();
//get method object (by passing in it's name and the list of argument types he's accepting - echo(String):
Method m = DsrProcessor.class.getMethod("echo", String.class);
//use reflection to invoke the method passing the instance of it's class and a list of arguments :
String methodReturnValue = (String) m.invoke(dsrProcessor, "Hello");
//do something with what the method returned
System.out.println(methodReturnValue);//prints: "echo:hello"
您还可以使用java.beans.Introspector类及其getBeanInfo方法之一。它返回一个BeanInfo实例,该实例引用了所有的属性描述符。