samedi 25 mars 2017

invoking bean's setter via reflection in android application

so basically i have a hash map where the key is day of the week from monday to sunday and my Time class also contains those fields, now i want to set key values in that class using reflection. This is my code:

WorkingTime wt = new WorkingTime();
         for (String key : timeToSend.keySet()){
            String methodExtentionL = key;
            String methodExtentionU = methodExtentionL.substring(0,1).toUpperCase()+methodExtentionL.substring(1);
            Log.i(TAG, "updateWorkingTime: key value "+methodExtentionU);

            try {
                String methodName = "set"+methodExtentionU;
                Method setMethod = wt.getClass().getDeclaredMethod(methodName,String.class);
                setMethod.invoke(wt,timeToSend.get(key));


            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

This could not be simpler, but it is still throwing method not found exception:

java.lang.NoSuchMethodException: setFriday [class java.lang.String]
W/System.err:     at java.lang.Class.getMethod(Class.java:624)
W/System.err:     at java.lang.Class.getDeclaredMethod(Class.java:586)

for every day. Looked all over stackoverflow and all articles for this kind off issue says that the code is supposed to look like that, but still nothing... Any help would be much appreciated. Thanks!





Aucun commentaire:

Enregistrer un commentaire