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<String> list = new ArrayList<String>();
// 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]));
}
}
}
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());
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有