我只是使用Method Reflection API创建一个通用方法。在这个方法中,我试图获得一个微粒方法(getter方法/ setter方法)值,但我卡住了我不知道该怎么做。我是Abel使用Method Reflection API获取所有方法Name而不是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();
}
}
答案 0 :(得分:0)
你是什么意思“方法的价值”你的意思是方法的返回类型,或者你想在它的父类的某个实例上调用该方法,可能有一些参数,然后得到值它返回?在这种情况下,如果您的方法不公开,则必须先在方法对象上调用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"
答案 1 :(得分:0)
您还可以使用java.beans.Introspector类及其getBeanInfo方法之一。 它返回一个BeanInfo实例,它引用所有属性描述符java.beans.PropertyDescriptor。