Numeric method parameters & reflection

Hi everyone,
I have a rather interesting problem for you...
I'm writing a program that will allow a user to call bean methods declaratively (i.e. in an XML doc) for any arbitrary bean. My problem is determining how to treat numeric parameter values. If a user wants to call doSomething(5), how do I know what Class type I need to pass in so that 5 matches the formal parameter type of the method being called? The actual parameter could be considered a byte, int, long, float or double.
Here's an example:
import java.lang.reflect.*;
public class ReflectTest
   public ReflectTest()
      try
         Class[] typeList = new Class[1];
         Object[] paramList = new Object[1];
         typeList[0] = Integer.TYPE;
         paramList[0] = new Integer(6);
         Method method = getClass().getMethod("doSomething",typeList);
         Object ret = method.invoke(this,paramList);
         System.out.println(ret.toString());
       catch(Exception ex)
         ex.printStackTrace();
   public String doSomething(int x)
      return "x="+x;
   public static void main(String[] args)
      ReflectTest reflectTest = new ReflectTest();
}This example works. But let's suppose the method signature was doSomething(long x). The getMethod() call would fail, because I had passed it a parameter of Integer.TYPE, and not Long.TYPE. Ironically, you could leave the call to invoke() as-is, it handles the widening automatically. Any ideas on how to go about this??
Thanks!

I'm writing a program that will allow a user tocall
bean methods declaratively (i.e. in an XML doc) for
any arbitrary bean. My problem is determining howto
treat numeric parameter values. If a user wants to
call doSomething(5), how do I know what Class typeI
need to pass in so that 5 matches the formalparameter
type of the method being called?When you say "call bean methods", I assume you mean
that you are setting properties on a JavaBean? If so,
then use the java.beans.Intospector
Also take a look at [url
http://jakarta.apache.org/commons/beanutils.html]the
Jakarta Commons BeanUtils libraryThanks, I think that the MethodUtils class might solve my problem.

Similar Messages

  • Automatic output of method parameters

    Hi,
    Sometimes I find myself System.out'ing all parameters of a method. Is there a one-step way to do this? A one-liner that will output all method parameters (using reflection I guess) of the method the code is running in.
    for e.g
    public Car makeCar(Color carColor, int noOfWheels){
    System.out.println(outputAllParametersOfThisMethod();
    }Console:
    carColor=Blue
    noOfWheels=4
    Appreciate any help that I can get!

    Hi,
    You can map these all parameters in Process instruction sheets and operator can view the PI sheet to view the process or qc parameter.
    Find below the link
    [http://help.sap.com/saphelp_47x200/helpdata/en/05/603bc6462311d182b50000e829fbfe/frameset.htm]
    http://help.sap.com/saphelp_47x200/helpdata/en/05/603bc6462311d182b50000e829fbfe/frameset.htm
    Sanjay

  • How to get names of method parameters ?

    How to get names of method parameters (Not only their type and value) is it only possible during debugging ??
    for example void myFunction(int a,int b)
    I need the "a" , and the "b" The issiue is about the java.lang.reflect.InvocationHandler ,
    and its method invoke(Object proxy,
    Method method,
    Object[] args)
    throws Throwable
    I Have the parameter objects themself and their types using method.getParameters() , this is fine ,, but i need the names of the parameters !!!

    If the class file was compiled without debug information included then it is impossible to get the original parameter names, as used in the source code.
    However, If the class file does include debug information, then the method names are hidden deep within the class file. You'd need to parse the class file yourself. Check out a copy of the Java VM Specification for a detailed format of the java class file format.
    It's not a trivial task to parse the java class file, and the VM spec isn't easy reading. You'd nearly be writing a class file disassembler.

  • 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);

  • Netbeans 6.0 - code completion of method parameters

    I just updated to NetBeans 6.0 and I find the code completion of method parameters very annoying and counter productive.
    It inserts the parameters as keywords when choosing a method from the list after pressing CTRL+SPACE.
    How can I switch this off?
    I searched the options and also the forum but didn't find a solution.

    I know that pressing space or whatever replaces the selected parameter. For a method with a single parameter is not a big problem but this is a poor workaround if a method has more parameters, like eg
    public static String formatDate(Date myDate, String myFormat)
    When typing
    Str.form<CTRL+SPACE,choose method, ENTER>
    it looks like
    Str.formatDate(myDate, errorMessage)
    Although myDate is selected and I can overwrite it, I have to proceed to the next parameter with CTRL+M instead of simply typing a comma. This is very annoying if a method has more parameters and as this annoyance occurs approx. every 5 lines that accumulates.

  • 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.

  • Get method parameters at runtime?

    Hey guys,
    is there a way to get the parameters of a methods parameters at runtime? I have a reference to an object and would like to know which paranmeter does a method have.?
       thx

    Hello
    You can use class CL_OO_CLASS (instance attribute METHOD_PARAMETERS ).
    Regards
      Uwe

  • Access fo Method parameters to Anonymous Class ?

    Can somebody please provide some more information on the statement below? I am also searching for some sample code implementations of it. It would help the cause better.
    +"Methods of the object of the anonymous class need access to final local variables and method parameters belonging to the method in which the anonymous class is defined. "+
    Thanks in Advance

    We're concerned here with "local" classes, i.e. classes defined inside methods (not all anonymous classes are local, and not all local classes are anonymous).
    The thing about local classes is that, unlike local variables etc., instances of a local class may survive the method returning. For example a local class might be a listener which gets added to a swing component, it could be a Runnable that get's launched as a thread.
    Local classes get to access local variables and parameters of the method in which they are declared but the variables or parameters have to be declared final because, since the class needs to be able to access the value of the local variable even after the method exits, and the variable ceases to exist, what actually happens it that the value of the variable is copied into a special field of the anonymous class, and if the variable could be changed after the class was defined, the two copies would then disagree.

  • Consolidating Decimal/Numeric type parameters in GP

    Hi guys,
    Need some pointers here. I'm calling a webservice CO to populate my Adobe form in GP on initiation. That works fine. But, some how or rather, i can't seem to consolidate any of the 'decimal/numeric' type parameters. The 'group' functionality is just greyed out. Eg. 'insurance' parameter in the WS is type 'decimal' (from ECC) and i've created a decimal type field in Adobe form too. HOwever, i can't seem to consolidate those type of parameters. Any reasons why? Thanks

    Hi,
    Just an update on this. The fields in the WebService are actaully of type 'CURR' (ABAP type). How do i map this in GP? Thanks

  • Method parameters

    Hello
    I'm usimg this code to get the local variables in case of a method entry:
                error = jvmti->GetLocalVariableTable(method, &entryCount, &localVariableEntry);
                if(error == JVMTI_ERROR_NONE) {
                    jvmtiLocalVariableEntry* entry = localVariableEntry;
                    for(int i = 0; i < entryCount; i++, entry++) {
                        cout << entry->signature << ":" << entry->name << endl;
                        jvmti->Deallocate(reinterpret_cast<unsigned char*>(entry->signature));
                        jvmti->Deallocate(reinterpret_cast<unsigned char*>(entry->name));
                        jvmti->Deallocate(reinterpret_cast<unsigned char*>(entry->generic_signature));
                    } // for
                    jvmti->Deallocate(reinterpret_cast<unsigned char*>(localVariableEntry));
                } else if(error = JVMTI_ERROR_ABSENT_INFORMATION) {
                    cout << "<NO LOCAL VARIABLE INFORMATION AVAILABLE>" << endl;
                } else {
                    cout << "<ERROR>" << endl;
                } // if...else if...elseNow I'm wondering how to find the method parameters in all this local variables...
    Is there a way to get obly the method parameters?
    Thank you very much and with kind regards
    Alexander Schell
    Edited by: EJP on 3/10/2011 20:24: added {noformat}{noformat} tags: please use them.
    Edit: Moved the first code-tag
    Edited by: user3948319 on 03.10.2011 08:02                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Hello and thanks for the answer...
    That was my first assumption...but after running the code I got some puzzling results...here's an example:
    callbackMethodEntry: methodName=reverse methodSignature=(Ljava/util/List;)V methodGenerigPtr=(Ljava/util/List<*>;)V classSignature=Ljava/util/Collections; thread=DestroyJavaVM
    I:i
    I:mid
    I:j
    Ljava/lang/Object;:tmp
    I:i
    I:mid
    Ljava/util/ListIterator;:fwd
    Ljava/util/ListIterator;:rev
    Ljava/util/List;:list
    I:size
    The method entered takes surely one argument - a list...but the list is not the first entry in the array which is created by calling getLocalVariableTable...so I'm a wee bit confused right now...
    I also don't understand under which circumstances the JVMTI_ERROR_ABSENT_INFORMATION error is raised...
    before I forget: Thanks for the tip with the code tags...I looked for something to mark the code but could not find it...
    With kind regards
    Alexander Schell

  • Can WLW display the real names of method parameters, not arg0, arg1...

    Hello
    I am new to Java development and as I used to work with MS.NET usually rely on parameter names, so that I don't have to read documentations each time I use a method. However I noticed that WLW replaces the names of method parameters with arg0, arg1, arg2 etc. Is there a way to somehow make WLW display the real argument names and not those argX strings?
    Thanks in advance.
    Best regards,
    Vasil Svetoslavov

    In wlw select...
    Tools
    +-- IDE Properties
    --Editor
    Ensure that the following are Checked
    Use Method Completion
    Use Parameter Completion

  • Final Method Parameters

    I've discovered I don't understand final method parameters as I thought I did. The language spec says you can declare a parameter as final, which I would have thought meant the method can't change it. But it turns out the called method can change it. In the following code, the change() method modifies the Test parameter quite easily.
    What am I misunderstanding here? If final doesn't keep the parameter from being modified, what does it do?
    public class Test
    private int privateValue = 0;
    * Stores the private value.
    * @param privateValue The value to store.
    public void setPrivateValue(int value)
       privateValue = value;
    public static void change(final Test test)
       test.setPrivateValue(3);
       test.setPrivateValue(4);
    * Program entry point
    * @param args Command line arguments
    public static void main(String[] args)
       Test test = new Test();
       Test.change(test);
       System.out.println("Done");
    }

    "Ahh, I see," said the blind carpenter, as he picked up his hammer and
    saw. I was indeed misunderstanding the use of final. It doesn't protect the
    reference object from changes, only the reference variable itself. Sigh...Just to be sure, is this your way of saying "I don't understand those explanations"?
    Look closely now :-)
    public class Test
    private int privateValue = 0;
    public void setPrivateValue(int value)
       privateValue = value;
    public static void change(final Test test)
       test.setPrivateValue(3); //this line does not even attempt to change the variable's value
       test.setPrivateValue(4); //neither does this one
      //incidentally and irrelevantly, they do ultimately change the value of another variable; a private field of the object pointed to by "test"
       //the next line DOES attempt to change the variable's value
       test = new Test(); //this does not compile because test is declared final
       test = null; //and again!
    public static void main(String[] args)
       Test test = new Test();
       Test.change(test);
       System.out.println("Done");
    }Variables (and parameters) hold primitives or references (they do not hold objects). For reference variables, they are either null or they point to an object. "final" applies to variables, not to the objects they may point to.
    If final
    doesn't keep the parameter from being modified, what
    does it do?So (I hope) you see, it does just that, generate a compile time error when the parameter is being modified.
    What am I misunderstanding here?I don't know. That's exactly what everyone else said.

  • The Method to reflect the changed OIM User Prifile to the Target Resource

    After completing the Trusted Reconciliation,
    The Method to reflect the changed OIM User Prifile to the Target Resource Account
    question)
    1. If i execute the Reconciliation of the target system, the current OIM User Profile information is automatically reflected in the target system

    Don't create threads for the same question:
    errorlog : Empty parent row cannot be updated ... what????

  • Web dynporo run-time methods parameters

    Hi,
    What is the best way of finding web dynpro run time method parameters ? I'm talking about methods like get_selected_parameters(), get_child_node etc..
    Many thanks

    Hi
    You can use the Web Dynpro Wizard this will give you the required coding
    or
    go to attributes of the view
    the context in the VIEW is of type IF_WD_CONTEXT_NODE. double click on this class you can find all the methods from there you can go to the parameter list
    for that matter if you know a class the same can be done
    Hope this will serve your purpose.
    Regards
    Ramchander Rao.K

  • 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

Maybe you are looking for