您的位置:首页 > 移动开发 > Objective-C

java利用反射实现Object-c中的KVC机制

2014-09-18 11:13 921 查看
Object-c中有个很牛逼的KVC机制,直接可以通过遍历一个类实例中的成员属性获取对应的值,即使没有getter,一样可以通过传入一个属性名获取对应的value,java中的反射机制一样可以实现这样的功能。上代码:

main方法

public static void main(String[] args) {

Person person = new Person();
person.setAge(23);
person.setName("liuchao");

java.util.List<phoneinfo> pInfos = new ArrayList<person phoneinfo="">();
PhoneInfo pInfo = new PhoneInfo();
pInfo.label = "label_phone";
pInfo.number = "180216xxxx";
pInfo.type = 0;
PhoneInfo pInfo1 = new PhoneInfo();
pInfo1.label = "label_phone1";
pInfo1.number = "1886232xxxx";
pInfo1.type = 1;
pInfos.add(pInfo1);
pInfos.add(pInfo);

person.setPhoneList(pInfos);

String name = (String) kvc(person, "name");
System.out.println(name);

int age = (Integer) kvc(person, "age");
System.out.println(age);

java.util.List<?>phoList = (java.util.List<?>) kvc(person, "phoneList");
for (Object object : phoList) {
String labelString = (String) kvc(object, "label");
String numberString = (String) kvc(object, "number");
int type = (Integer) kvc(object, "type");
System.out.println(labelString + "  " + numberString + "   " + type);
}
}
</person></phoneinfo>


kvc方法

private static Object kvc(Object object, String key) {
Field[] fields = object.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
String keyName = field.getName();
if (keyName.equals(key)) {
try {
Object obj = field.get(object);
return obj;
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}

}
return null;
}


person类

public class Person {

String name;
int age;
private List<phoneinfo> phoneList = new ArrayList<phoneinfo>(); // 联系号码

public static class PhoneInfo {
/** 联系电话类型 */
public int type;
/** 联系电话类型标签 */
public String label;
/** 联系电话 */
public String number;
}

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public List<phoneinfo> getPhoneList() {
return phoneList;
}
public void setPhoneList(List<phoneinfo> phoneList) {
this.phoneList = phoneList;
}

}


运行结果:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Java kvc