反射配对儿XML

来源:互联网 发布:js window发送url 编辑:程序博客网 时间:2024/05/23 19:17
private void setQuake(XmlPullParser xpp) throws Exception {
        try {
            Class<?> c = Class.forName(Quake.class.getName());
            Field[] fs = c.getDeclaredFields();
            final Quake quake = (Quake)c.newInstance();
            Method m = null;
            for (Field field : fs) {
                // 属性名
                String methodName = field.getName();
                if (methodName.equals(xpp.getName())) {
                    String value = xpp.nextText();
                    // 获得每个属性的set方法
                    if (field.getGenericType().toString().equals("class java.util.Date")) {
                        m = c.getMethod("set" + getMethodName(methodName),
                                java.util.Date.class);
                        m.invoke(quake, Date.parse(value));
                    } else if (field.getGenericType().toString()
                            .equals("class java.lang.String")) {
                        m = c.getMethod("set" + getMethodName(methodName), String.class);
                        m.invoke(quake, value);
                    } else if (field.getGenericType().toString()
                            .equals("class android.location.Location")) {
                        m = c.getMethod("set" + getMethodName(methodName), Location.class);
                        m.invoke(quake, value);
                    } else if (field.getGenericType().toString().equals("double")) {
                        m = c.getMethod("set" + getMethodName(methodName), double.class);
                        m.invoke(quake, Double.parseDouble(value));
                    }
                    Log.i("info",m.getName());
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            addNewQuake(quake);
                        }
                    });
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    protected void addNewQuake(Quake quake) {
        earthquakes.add(quake);
        aa.notifyDataSetChanged();
    }


    private static String getMethodName(String fildeName) throws Exception {
        byte[] items = fildeName.getBytes();
        items[0] = (byte) ((char) items[0] - 'a' + 'A');
        return new String(items);
    }
0 0
原创粉丝点击