更新时间: 2016年8月5日15:06:22提交: 静县
以下编辑器将带给您Java反射,以根据不同的方法名称动态调用不同的方法(示例). 编辑认为它很好,因此动态方法调用 为什么不安全,我现在将与您分享并提供参考. 让我们一起关注小编,看看
列表页面的字段需求可以根据用户的偏好进行排序,因此每个用户的字段都对应一个不同的顺序(字段顺序存储在中),我们从中取出的值是一个对象,但是前端通过它使用的是ajax和json数组,因此它面临着对象到json的转换问题: 1.每个用户的字段顺序都不固定,并且代码也很难写. 2.根据用户字段的顺序,取值,如果由if判断动态方法调用 为什么不安全,则每个值然后调用不同的方法,如果有条件语句,则过多. 然后我看着反射.
模型类,与普通模型相同
public class Person {
private String name;
private int age;
private String address;
private String phoneNumber;
private String sex;
public String getName() {
return name;
}
// 以下是get 和set方法,省略。
}
测试班
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
public class Test {
// init person object.
private Person initPerson() {
Person p = new Person();
p.setName("name");
p.setAge(21);
p.setAddress("this is my addrss");
p.setPhoneNumber("12312312312");
p.setSex("f");
return p;
}
public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
Test test = new Test();
Person p = test.initPerson();
List list = new ArrayList();
// Add all get method.
// There is no ‘()' of methods name.
list.add("getName");
list.add("getAge");
list.add("getAddress");
list.add("getPhoneNumber");
list.add("getSex");
for (String str : list) {
// Get method instance. first param is method name and second param is param type.
// Because Java exits the same method of different params, only method name and param type can confirm a method.
Method method = p.getClass().getMethod(str, new Class[0]);
// First param of invoke method is the object who calls this method.
// Second param is the param.
System.out.println(str + "(): Get Value is " + method.invoke(p, new Object[0]));
}
}
}
可以根据获取的字段从对象中遍历样本以获得相应的值
以上方法是将get方法名称添加到列表中,以便根据相应的get方法名称获取值. 如果前台仅传递属性名称,那么我们必须转换为相应的get方法,麻烦.
public static void getValueByProperty(Person p, String propertyName) throws IntrospectionException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
// get property by the argument propertyName.
PropertyDescriptor pd = new PropertyDescriptor(propertyName, p.getClass());
Method method = pd.getReadMethod();
Object o = method.invoke(p);
System.out.println("propertyName: " + propertyName + "\t value is: " + o);
}
public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, IntrospectionException {
Test test = new Test();
Person p = test.initPerson();
// get all properties.
Field[] fields = p.getClass().getDeclaredFields();
for (Field field : fields) {
getValueByProperty(p, field.getName());
}
}
通过这种方式,您可以直接通过传递的propertyName获取相应的值
上述Java反射根据不同的方法名称动态调用不同的方法(示例). 这就是我与您共享的所有内容. 我希望能给您参考,也希望您能支持该脚本主页.
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/tongxinshuyu/article-184792-1.html