mercredi 23 septembre 2015

Java Reflection Method Invocation with Unknown Bean Structure

I have written some code that feels like a hack.

    private void handleSpecialCase(Method mvw, InterfacePersistenceBean pObj, AbstractBeanWrapper wrapper, String methodCore)
        throws TestStructureException
    {
       try
      {

        Parameter p= getParameterByName(methodCore, this.PREFIX_SET,pObj);
        Method mp=null;
        try
        {
             mp = pObj.getClass().getMethod("set"+methodCore, new Class[]
            { p.getType() });
        }
        catch(NoSuchMethodException e)
        {
             mp = pObj.getClass().getDeclaredMethod("set"+methodCore, new Class[]
                        { p.getType() });
        }

        Method serviceMethod = beanByIdService.getClass().getMethod("get"+methodCore, new Class[]
                { java.lang.Long.class });

        InterfacePersistenceBean beanToSet=(InterfacePersistenceBean)serviceMethod.invoke(beanByIdService, mvw.invoke(wrapper));
        mp.setAccessible(true);
        mp.invoke(pObj, beanToSet);
    }
    catch (Exception e)
    {
        SS.getLogger().error(e.getMessage()+" "+e.getCause(),e);
        throw new TestStructureException(e.getMessage(), e.getStackTrace());
    }

  • The inner try block (i.e., getMethod() ) will get methods from superclasses, but will not get protected or private methods. If a method is protected it throws NoSuchMethodException.

  • Hence the inner catch block uses getDeclaredMethod() which will get protected and private methods but throw NoSuchMethodException on superclass methods.

  • A protected/private superclass method would always throw an exception here which is fine for my purposes but nonetheless inelegant.

Can someone suggest a more flexible, robust, and elegant approach (preferably without using annotations)?

Thanks a million





Aucun commentaire:

Enregistrer un commentaire