Invoking method with reflection - with String[] params

Hi there,
I have a method that I need to call with reflection. This method has one parameter
public void setArgs(String args[])
I'm trying to invoke it by reflection. I tryied this but didn't work:
Class[] parameterArgs = {String[].class};
Method mCallArgs = objClasseChiamata.getClass().getMethod("setArgs",parameterArgs);
Object[] nomeArgs = new Object[]{"Luca","Alessio"};
//I try too:
//String[] nomeArgs = new String[]{"Luca","Alessio"};
mCallArgs.invoke(objClasseChiamata ,nomeArgs);     
It compile ok,
but in Runtime I find this error:
java.lang.IllegalArgumentException
java.lang.Throwable()
java.lang.Exception()
java.lang.RuntimeException()
java.lang.IllegalArgumentException()
java.lang.Object java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object [])
void reflection.TestReflection.main(java.lang.String [])
Thank you,
Alessio

The thing that goes in the Object[] is the paramaters. The parameter is one String[], not two Strings:
Object[] nomeArgs = { new String[] {"Luca", "Alessio"} };
mCallArgs.invoke(objClasseChiamata ,nomeArgs);
// or
mCallArgs.invoke(objClasseChiamata, new Object[] { new String[] {"Luca", "Alessio"} });Note that there's no reason to use "new Object" when you're initializing a named array reference (just like you initialized the Class[] above).

Similar Messages

  • Invoking methods through reflection

    I need to check a property in the javax.faces.component.html.HtmlInputText.
    If i do it in the following manner,I get things fine:
    if(comp.getClass().getName().equalsIgnoreCase("javax.faces.component.html.HtmlInputText")) {
    String getter=((javax.faces.component.html.HtmlInputText)comp).getOnfocus();
    if(getter!=null) {
    System.out.println(getter);
    But if i invoke it through reflection,I get nothing.
    I am doing the following:
    Class reqClass = Class.forName("javax.faces.component.html.HtmlInputText");
    Method[] methodList = reqClass.getDeclaredMethods();
    int methodIdx = 0;
    for (int i = 0; i < methodList.length; i++) {
    Method reqMethod =methodList;
    if(reqMethod.getName().indexOf("getOn")== 0) //method starts with getOn
    // method accepts parameters, define the types in order here as Class[]
    Class[] classParams = new Class [] {};
    // set the method of the class object
    Method method = reqClass.getMethod( reqMethod.getName(), classParams );
    // pass values to fill parameters of method
    Object[] arguments = new Object [] {};
    // invoke method via reflection.Note that class has default constructor
    Object retobj=method.invoke( reqClass.newInstance() ,
    arguments );
    String getterResult = (String)retobj;
    if(getterResult!=null)
    System.out.println(reqMethod.getName() + " ## " + getterResult);
    What am i doing wrong while invoking the method through reflection.
    I get no exception either.

    It is a simple typo.
    An alternative I tried is the following ,but that does not work either.
    Class reqClass = Class.forName("javax.faces.component.html.HtmlInputText");
    Method[] methodList = reqClass.getDeclaredMethods();
    int methodIdx = 0;
    for (int i = 0; i < methodList.length; i++) {
    Method reqMethod =methodList;
    if(reqMethod.getName().startsWith("getOn")) //method starts with getOn
    System.out.println(reqMethod.getName());
    // pass values to fill parameters of method
    Object[] arguments = new Object [] {};
    // invoke method via reflection
    Object retobj=reqMethod.invoke( reqClass.newInstance(), arguments );
    String getterResult = (String)retobj;
    if(getterResult!=null)
    System.out.println(reqMethod.getName() + " ## " +getterResult);

  • Invoking a method using reflection with json data as argument

    Hi,
    I want to invoke a method using reflection and this method have one argument . Now I want to pass a json data as an argument to this method .Please see the following code.
    int HelloWorld(int Id){
    return Id;
    json data{"Id":43}
    how can I use the reflection to use the json.
    Please provide your guidelines

    Thanks for your reply, I am building a windows console application .And I want to convert the json data to object array to use in Method Base.Invoke method.
    Regards,
    Ethan
    Maybe you could select the correct language development forum here:
    http://social.msdn.microsoft.com/Forums/vstudio/en-US/home?category=vslanguages&filter=alltypes&sort=lastpostdesc
    Best Regards,
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Invoking methods extracted from a string?!?

    Hi everybody. I hope the subject is not confusing. What I'm really looking for is some Perl-like behaviour in Java. In Perl its possible to execute subroutines (basicly methods) extracted from a string ("&sub()"). Is there anything similar in Java?
    What I would like to do is to process a string and if it has a method (object.getTime()), the method will be called and the return value stored in its place.
    Please let me know if more explanation is needed.
    Thanks in advance for all the help!
    Leo.

    I use a language called MUMPS where you can do that as well - execute strings as commands etc. I don't know much about Reflection but it looks like you can get method (Objects) from strings and execute them as well ...

  • Invoking methods on JMX with user defined objects.

    Hello, All.
    Here is the problem description: We need to expose methods on JMX which takes some object of user defined class. We are not able to do that. Meaning, it is not getting enabled and if we invoke through code it says exception with serialization things. So we tried to make user defined class to implement serialization by making it to implement Serializable [though just adding serialization id]. But still we are getting the same problem. So I think we are missing some small step; as we are completely new this we are looking for some help in how to provide methods on jmx which accepts arguments of user defined type.
    Thanks,
    Prasanna.

    When executing an operation via JMX using JConsole, I get the following error:
    Problem invoking getManifest : java.rmi.UnmarshallException: Error unmarshalling return: nested is: java.lang.ClassNotFoundException: foo.bar.InernalServiceException (no security manager: RMI class loader disabled)
    Code snippet:
    public ArrayList getManifest(String s) throws InternalServiceException, MBeanException{
    String path = ".\\foo_services.jar"; // Invalid path on purpose to test exception...
    File file = new File(path);
    FileInputStream fileInput;
    try {
    fileInput = new FileInputStream(file);
    } catch (FileNotFoundException e) {
    String msg = "The manifest file is not found in the given path";
    if (logger.isErrorEnabled()) logger.error(msg);
    throw new InternalServiceException(msg, ErrorConstants.JMX_FILE_NOT_FOUND);
    If I throw new RuntimeException(msg, e) instead of InternalServiceException(msg, ErrorConstants.JMX_FILE_NOT_FOUND), it works and I get the appropriate exception.
    What is the reason for this?

  • Invoke method dynamically  based on string name.

    In my code i have some 50 odd if else condition:
    if(command.equals("abc"))
    //call abc method
    abc();
    else if(command.equals("xyz"))
    // call xyz();
    and so on........
    now based on command string i need to call a method whose name is identical to command string.
    I have used reflection to do this and it works. But just need to know ,
    is there any other approach available?
    Also, it is better to use reflection or just write 50 if else statements and call each function.
    TIA,
    Sachin

    hey i asked the same question a little while ago and got some
    very good feedback at this thread
    http://forum.java.sun.com/thread.jspa?threadID=646255
    i had written some test code but i cant find it.
    you will be looking for this kind of stuff though
    (this isnt intelligible code)
    Object o = Class.forName("hto");
    Field[] fields = ht.getClass().getDeclaredFields();
    Class class1 = ( fields[1].getType() );
    Class class2 = Class.forName("MyClassName");
    Class[] param = { value.getClass() };
    Object[] invokeParam = { value };
    Class[] prim = { Class.forName("HackThis") };
    Method method = ht.getClass().getMethod("set" + var, param);
    method.invoke(ht, invokeParam);

  • Invoking method thru reflection

    I have got a method which takes in a primitive datatype (eg. int) as its argument. One of the parameters of getMethod() in the class Class is Class[] representing the various args of the method to be invoked. How do I represent the primitive data type as part of this Class[]?
    Your reply will be greatly appreciated.

    import java.lang.reflect.*;
    public class TT {
         public static void loadClass(String className,String methodName,String arg)
              Class          l_class;
              java.lang.Object          returnValue=new Object();
              try{
              Class[] parameterTypes = new Class[] { int.class };
                   l_class=Class.forName(className);
                   java.lang.Object o = l_class.newInstance();
                   Method method =l_class.getMethod(methodName, parameterTypes);
                   java.lang.Object arguments[] = new java.lang.Object[1];
                   arguments[0] =new Integer(arg) ;
                   returnValue=method.invoke(o, arguments);
                   if( returnValue instanceof Integer ){
                        System.out.println("Int value = "+((Integer)returnValue).intValue() );
                   else{
                        System.out.println("Int value false");
              catch(NoSuchMethodException nsme)          {          }
              catch(IllegalArgumentException iae){     }
              catch(InvocationTargetException ite)     {          }
              catch(Exception e){ }
              return ;
         public static void main(String[] args) throws Exception
              loadClass( args[0] , args[1], args[2] );
    /// Example.java
    public class Example
         public int get(int i){
              return i;
         public static void main(String[] args)
              System.out.println("Hello World!");
    [email protected]

  • Help with Creating a method that takes a string of arrays?

    i just begin my intro to programming and im a little stuck we had to write a program yesterday and i managed fine then today we had to work with arrays and i dont know much about arrays so im hoping someone here can point me in the right direction. This is what he wants *"Create a method called "printReceipts" that takes a String array of names (first names only) and prints out a message to customers using their name and telling them what customer number they are. The method should work with an array of any size."*
    Im not asking you to do it for me just i gues point out what methods i need to change thanks
    package edu.nmhu.cs245;
    public class Assignment1 {
         private String messagePrefix1 = "Hello ";
         private String messagePrefix2 = ", \n";
         public String[] getName() {
              String[] names = new String[] {"Lonny", "Gil", "Hosein"};
              return names;
         public String getCompleteMessage(String name, String message) {
              String completeMessage = messagePrefix1 + name + messagePrefix2 + message ;
              return completeMessage;
          * @param args
         public static void main(String[] args) {
              Assignment1 a = new Assignment1();
              String[] names = a.getName();
              for (int i = 0; i < names.length; i++) {
                   String printReciepts = a.getCompleteMessage(names,"You are customer number#" +(i+1));
                   System.out.println(printReciepts);
                   System.out.println();

    Focus! You should know what every single line of code is supposed to do! And they should all add up to a larger goal.
    Don't just put in stuff that seems like it's part of a relevant example.
         public String[] getName() {
              String[] names = new String[] {"Lonny", "Gil", "Hosein","Sam"};
              return names;
         }Are you supposed to do it that way? Or did it come with the assignment? It's (probably) fine for a homework assignment, but it's hardcoded data, which in practice one normally doesn't do.
              String completeMessage = messagePrefix1 + names + messagePrefix2 + messageSuffix ;Why do this? You're supposed to produce a receipt per use, not for all users at one.
              for (int i = 0; i < names.length; i++) OK, good. You could have used a foreach loop but this is fine.
                   String printReciepts = a.getCompleteMessage(names,"You are customer number#" +(i+1));What is "getCompleteMessage"?  You didn't define it.  Do you think that it is created implicitly because of the local String variable you created called "completeMessage"?  It doesn't.           String2 a = new String2();Don't call your class "String2".  It doesn't mean anything.  Name it after the assignment or something.           a.printReceipts(names);"names" isn't defined.  There's a local variable called "names" in the getNames method, but it doesn't exist when you call this and it's unavailable anyway.  You probably meant to do           a.printReceipts(a.getName());                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • GET Method with long query string

    Hi there,
    Not sure if this has already been answered. Sorry if it has!
    I have a Biztalk application which does a pass-through for all http requests. It is using WCF-WebHttp transport type with URL mapping of /*.
    It works fine except for GET method that has query string longer than 256 characters. It chokes with following exception:
    The adapter "WCF-WebHttp" raised an error message. Details "System.ArgumentOutOfRangeException: The value of promoted property cannot exceed 256 characters. Property "To" Namespace "http://schemas.microsoft.com/BizTalk/2006/01/Adapters/WCF-properties".
    My question is is there a workaround for this e.g. extend the string length limit? 

    Hi Karsten,
    Try giving the one part of URL in address box and other pass the arguments inside HTTP Method and URL Mapping dialog.
    Eg:
    Address (URI) : https://btstecheddemostorage.blob.core.windows.net
    <BtsHttpUrlMapping>
    <Operation Name="ListFiles"
    Method="GET" Url="/{mycontainer}?restype=container&amp;comp=list"
    /> </BtsHttpUrlMapping>
    Thank YOu,
    Tamil

  • String Param tag replace with Br tag

    original text:
    <P ALIGN="LEFT">sample text1</P><P ALIGN="LEFT">sample text2</P><P ALIGN="LEFT">sample text3</P>
    I need to: <br/>sample text1<br2>sample text2<br2>sample text3
    can help me

    var reg:RegExp = /\<\/?P.*?\/?\>/igm;
      var _m=messageField.htmlText//<P ALIGN="LEFT">sample text1</P><P ALIGN="LEFT">sample text2</P><P ALIGN="LEFT">sample text3</P>
      _m=_m.replace(reg, '<br/>');
    trace(_m) //  "<br/>sampletext1<br/><br/>sampletext2<br/><br/>sampletext3<br/>"
    Iam getting double breaks i need only one break.
    Re: String Param tag replace with Br tag 

  • Error while transforming XSLT by calling function with Reflection API

    Hi,
    I'm new to Reflection API. I want to call function from the jar file which is not in my application context. So I have loaded that jar ( say XXX.jar) file at runtime with URLClassLoader and call the function say [ *myTransform(Document document)* ]. Problem is that when I want to transform any XSLT file in that function it throws exception 'Could not compile stylesheet'. All required classes are in XXX.jar.
    If I call 'myTransform' function directly without reflection API then it transformation successfully completed.
    Following is code of reflection to invoke function
            ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
            URLClassLoader loader = new URLClassLoader(jarURLs, contextCL);
            Class c = loader.loadClass(fullClasspath);
            Constructor constructor = c.getDeclaredConstructor(constructorParamsClasses);
            Object instance = constructor.newInstance(constructorParams);
            Method method = c.getDeclaredMethod("myTransform", methodParamsClasses);
            Object object = method.invoke(instance, methodParams);Following is function to be called with reflection API.
    public Document myTransform ( Document document ) {
    // Reference of Document (DOM NODE) used to hold the result of transformation.
                Document doc = null ;
                // DocumentBuilderFactory instance which is used to initialize DocumentBuilder to create newDocumentBuilder.
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance () ;
                // Reference of DocumentBuilder used to create new Document (DOM NODE).
                DocumentBuilder builder;
                try {
                      // Initialize DocumentBuilder by using DocumentBuilderFactory instance.
                      builder = factory.newDocumentBuilder ();
                      // Initialize new document instance by using DocumentBuilder instance.
                      doc = builder.newDocument () ;
                      // Creates new DOMSource by using document (DOM NODE) which is coming through current transform() method parameter.
                      DOMSource domsource = new DOMSource ( document ) ;
                      // Creates new instance of TransformerFactory.
                      TransformerFactory transformerfactory = TransformerFactory.newInstance () ;
                      // Creates new Transformer instance by using TransformerFactory which holds XSLT file.
                      Transformer transformer = null;
    ********* exception is thrown from here onward ******************
                      transformer = transformerfactory.newTransformer (new StreamSource (xsltFile));
                      // Transform XSLT on document (DOM NODE) and store result in doc (DOM NODE).
                      transformer.transform ( domsource , new DOMResult ( doc ) ) ;
                } catch (ParserConfigurationException ex) {
                      ex.printStackTrace();
                } catch (TransformerConfigurationException ex) {
                      ex.printStackTrace();
                } catch (TransformerException ex) {
                     ex.printStackTrace();
                } catch (Exception ex) {
                     ex.printStackTrace();
                //holds result of transformation.
                return doc ;
    }Following is full exception stacktrace
    ERROR:  'The first argument to the non-static Java function 'myBeanMethod' is not a valid object reference.'
    FATAL ERROR:  'Could not compile stylesheet'
    javax.xml.transform.TransformerConfigurationException: Could not compile stylesheet
            at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl.newTemplates(TransformerFactoryImpl.java:829)
            at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl.newTransformer(TransformerFactoryImpl.java:623)
            at com.actl.dxchange.utilities.Transformation.transform(Transformation.java:83)
            at com.actl.dxchange.base.BaseConnector.transform(BaseConnector.java:330)
            at com.actl.dxchange.connectors.KuoniConnector.doRequestProcess(KuoniConnector.java:388)
            at com.actl.dxchange.connectors.KuoniConnector.hotelAvail(KuoniConnector.java:241)
            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
            at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
            at java.lang.reflect.Method.invoke(Method.java:585)
            ...........

    Hi,
    Thanks for response.
    Following is code for setting 'methodParamsClasses' array object. I do ensure that Document is not null and valid. My application is web application.
    Document requestObj = /* my code for generating Document object*/
    Object[] methodParams = new Object[]{requestObj}
    Class[] methodParamsClasses = new Class[]{};
                if (methodParams != null) {
                    methodParamsClasses = new Class[methodParams.length];
                    for (int i = 0; i < methodParams.length; i++) {
                        if (methodParams[i] instanceof Document) {
    /************** if parameter is instance of Document then I set class type as "Document.class" ***********/
                            methodParamsClasses[i] = Document.class;
                        } else {
                            methodParamsClasses[i] = methodParams.getClass();

  • Reflection with proxy home class

    Hello !
    I'm trying to perform some common code to invoke method on home computed with the reflection API (code without try/catch):
    Object homeref = initial.lookup(compName);
    Class xClass = homeref.getClass();
    InvocationHandler invctHandler = Proxy.getInvocationHandler(homeref);
    Method findByPrimaryKey = xClass.getMethod("findByPrimaryKey", new Class[] {scopedAidClass});
    object = invctHandler.invoke(homeref, findByPrimaryKey, new Object[] {scopedAid});
    at runtime I get an invalid invocation exception.
    I have define correctly the ejb-external-ref to be able to use the bean on which I'm invoking the home.
    I know somewhere the code has to be downloaded into the proxy. So I tried to narrow the homeref with the PRO - though in local:
    Object homestub = (Object)PortableRemoteObject.narrow(homeref, thisHomeClass);
    without any effect, still getting the same proxy and getting the same exception at runtime.
    Thank you for any help.
    seb.

    Hi ,
    Instead of using below line of code
    object = invctHandler.invoke(homeref, findByPrimaryKey, new Object[] {scopedAid});
    use this :
    object = findByPrimaryKey .invoke(homeref, new Object[] {scopedAid});
    I hope it shows some solution to your problem.
    Regards,
    Santhosh

  • Casting objects with reflection possible?

    I have this code:
    String className = "com.xyz.MeasurementUnit";
    Class provider = Class.forName(className + "Provider");
    Object object = context.getContractProxy(provider);The last line returns an object of type object. I must execute the method getIsoId(...) on that object. But to do that, I think I have to cast it first to the object type MeasurementUnitProvider.
    Is this possible with reflection? Is it somehow possible to solve what I want to do?

    If MeasurementUnitProvider is an interface that is known at compile time, then the cast can be made in the usual way MeasurementUnitProvider unitProvider = (MeasurementUnitProvider)context.getContractProxy(provider);If the interface is not known at compile time, then the object reflecting the method can be obtained from the Class object by name and parameter type. For reflective method invocation, no cast is required.
    Pete

  • Difference between invoking a method using reflect.proxy and reflect.Method

    Could any one tell me the difference between invoking a method using reflection java.lang.reflect.Method and java.lang.reflect.Proxy
    using both the class, we can invoke a method at runtime
    1)
    Method mthd=cl.getMethod("methodName",parameterName);
    Integer output=(Integer)mthd.invoke(new RunMthdRef(),input);
    2)
    Proxy.newProxyInstance(super.getClass().getClassLoader(), new Class[] { adapter }, new SomeClass(this));
    Does anybody have any idea?

    The two idioms are fundamentally different. Using java.lang.reflect.Method is how we call a method on a class, using Proxy is how we intercept that method call. An exercise for you, to illustrate that they do not do the same thing: write a simple class with one method, then use java.lang.reflect.Method to invoke that method, and then use a Proxy to invoke that method

  • Dealing with an empty string parameter

    I'd think this should be simple but is driving me nuts. I have a string parameter (lets call it Foo) that is being passed from my C# application to a CR subreport. For this parameter field I have a formula associated with "Display String" similar to this:
    if (IsNull({?Foo}) or (length({?Foo}) = 0)) then
        "Value is empty"
    else
        "Value is " + {?Foo}
    I can never get the "Value is empty" line to appear! I've tried lots of suggestions:
    1. trim and check result equal to '' (two single quotes)
    2. test if equal to "".
    3. Adding false to Suppress.
    It appears that if this parameter is the empty string CR simply does nothing with my formulas and the entire parameter field is skipped.
    If I pass "null" (or any other special string) instead of "" from my C# code and then change the above test to check for that value as shown below things work properly.
            if (IsNull({?Foo}) or ({?Foo} = "null") then
    However I really don't like testing for a special string as there is the remote possibility that it could be the actual value of the parameter.
    Any help most appreciated.
    Dick

    Not surprised and willing to bet there will be a simple answer to this!
    There is something most odd happening when the string value is empty.
    Let me answer your questions.
    1 - How are you setting your parameter value?
    Since I want to be able to pass parameters to the base report as well as its subreports I'm using this method:
            protected void setParameter(string parameterName, object value)
                ParameterFields fields = report.ParameterFields;
                for (int i = 0; i < fields.Count; i++)
                    if (fields<i>.Name.Equals(parameterName))
                        string reportName = fields<i>.ReportName;
                        if (string.IsNullOrEmpty(reportName))
                        {   // give to base report
                            report.SetParameterValue(parameterName, value);
                        else
                        {   // give to subreport
                            report.SetParameterValue(parameterName, value, reportName);
    2 - What OS and service pack are you on?
    Windows XP, SP 3. All updates from MS installed.
    My development environment is either of these two:
    a. VS 2008. Version 9.0.30729.1 SP. ,NET Framework 3.5 SP1
    b. VS 2010 Version 4.0.30319
    3 - What platform are you targeting?
    For now just running on my XP PC but have tested our app on XP, Win7, and Vista. 32 and 64-bit version of each.
    4 - Is this a win or web form application? Win app
    5 - What is the version of your CrystalDecisions.CrystalReports.Engine?
    Version: 12.2.0.290, Product Type: Full
    6 - What is the version of crpe32.dll do you have on your machine?
    I only have one instance of this file in this directory:
         C:\Program Files\Business Objects\BusinessObjects Enterprise 12.0\win32_x86
    7 - Did you have one of our betas on this machine? No
    Edited by: dcowan on Dec 7, 2010 2:10 AM
    I needed to finish this so I'm closing it.
    In my C# code I placed the following:
                        if (string.IsNullOrEmpty(value))
                            value = "!_Empty_!";
    and in the CR formula I used:
           (IsNull({?CoBrandName}) or ({?CoBrandName} = "!_Empty_!"))
    Everything is now working just as I want. Not an ideal solution but I gave up.

Maybe you are looking for