dimanche 8 juillet 2018

Android - How to do Reflection properly?

I want to access and change length of months in Datepicker, therefor I do like this: try { Field[] fields = object.getClass().getDeclaredFields();

        for (Field field : fields) {
            if (field.getName().equals("mDelegate")) {
                field.setAccessible(true);
                object = field.get(object);
                fields = object.getClass().getDeclaredFields();
                break;
            }
        }

        for (Field field : fields) {
            if (field.getName().equals("mDaySpinner")) {
                field.setAccessible(true);
                field.set(object, /*anything like*/ 30);
                Object innerObject = field.get(object);
                Method method = innerObject.getClass().getDeclaredMethod("setMaxValue", int.class);
                method.setAccessible(true);
                method.invoke(innerObject, (Object) /*anything like*/ 30);
            }
        }

        Method[] methods = object.getClass().getDeclaredMethods();

        for (Method method : methods) {
            if (method.getName().equals("updateSpinners")) {
                method.setAccessible(true);
                method.invoke(object);
                break;
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}





Aucun commentaire:

Enregistrer un commentaire