about how to invoke a method using Reflection

13 views
Skip to first unread message

Alonso Isidoro Roman

unread,
Nov 4, 2013, 6:24:58 AM11/4/13
to google-code...@googlegroups.com
Hi everyone, first at all, my apologies if this question is already answered. Previously i have done some research and nothing useful.

I need to invoke  a setter method from a class which extends from another one, the class belongs to a third party so i dont have any chance to modify it for my purposes.

SIPWebContext extends SipStandardContext

I need to invoke the setApplicationName method located in SipStandardContext:

    public void setApplicationName(String applicationName) {
        this.applicationName = applicationName;
    }

the code:

        Set<Method> setters = getAllMethods(org.mobicents.as7.deployment.SIPWebContext.class,
                                            withModifier(Modifier.PUBLIC),
                                            withPrefix("setApplicationName"),
                                            withParametersAssignableTo(String.class),
                                            withParametersCount(1));
/

        Object ctx = servletConfig;
        //how do i get an instance from this class (org.mobicents.as7.deployment.SIPWebContext.class) if i dont have any interface?

        Object ctx3 =null;
        try {
            Field fWrapper = ctx.getClass().getDeclaredField("wrapper");
            fWrapper.setAccessible(true);
            Object ctx2 = fWrapper.get(ctx);
            Field fParent = Class.forName("org.apache.catalina.core.ContainerBase").getDeclaredField("parent");
            fParent.setAccessible(true);
            ctx3 = fParent.get(ctx2);
            if (ctx3.getClass().getName().equals("org.mobicents.as7.deployment.SIPWebContext")) {
              
                for (Method aMethod : setters) {
                    System.out.println("METODO SET: " + aMethod.getName());
                    if ("setApplicationName".equals(aMethod.getName())) {
                        System.out.println("FOUND setApplicationName method!!!");
                        //i need that ctx3 be an living instance from org.mobicents.as7.deployment.SIPWebContext class
                        //necesitas que ctx3 sea una instancia del objeto!!!, si no da un  java.lang.IllegalArgumentException: object is not an instance of declaring class
                        aMethod.invoke(ctx3, new Object[] {newAppNameFromCallServiceString});
                        break;
                    }
                }
              
            }
        } catch (java.lang.Throwable xcp) {
            xcp.printStackTrace();
        }

Is it possible to do it? could someone help me?

alonso
Reply all
Reply to author
Forward
0 new messages