Method.invoke args

I have a method:
Method m = String.class.getMethod("charAt",new Class[]{int.class});
then how can i invoke this method as the effect of "haha".charAt(2);
m.invoke("haha",new Object[]{new Integer(2)});
m.invoke("haha",new Object[]{2});
cannot work!,

Method meth = String.class.getMethod("charAt",new Class[]{int.class});
System.out.println(meth.invoke("0123", new Object[] {new Integer(2)}));prints out "2".
Is your confusion about how to put a primitive int into a Object array? For primitive args, you use the object wrapper. Since the Method object you're calling invoke on was specified to be the one taking the int primitive (with "int.class"), the conversion from your Integer arg to the needed int arg is made automatically.

Similar Messages

  • How to trap null return values from getters when using Method.invoke()?

    Hi,
    I am using Method.invoke() to access getters in an Object. I need to know which getters return a value and which return null. However, irrespective of the actual return value, I am always getting non-null return value when using Method.invoke().
    Unfortunately, the API documentation of Method.invoke() does not specify how it treats null return values.
    Can someone help?
    Thanks

    What do you get as a result?I think I know what the problem is.
    I tested this using following and it worked fine:
    public class TestMethodInvoke {
    public String getName() {
    return null;
    public static void main(String args[]) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    Object o = new TestMethodInvoke();
    Class cls = o.getClass();
    Method m = cls.getMethod("getName", (Class[]) null);
    Object result = m.invoke(o, (Object[])null);
    if (result == null) {
    System.err.println("OK: Return value was null as expected");
    else {
    System.err.println("FAILED: Return value was NOT null as expected");
    However, when I use the same technique with an EJB 3.0 Entity class, the null return value is not returned. Instead, I get a String() object. Clearly, the problem is the the EJB 3.0 implementation (Glassfish/Toplink) which is manipulating the getters.
    Regards
    Dibyendu

  • Method.invoke hangs. HELP

    that is:
    Method.invoke(obj,args)
    It works just fine the first dozen or 2 times, same obj, same args. No prob.
    Then it hangs.
    No exception message. nothing. It just stops at invoke. And the Task Manager says the thread is eating 99% of the CPU, so it's spinning away in some loop I guess. The method getting invoked DOES NOT get called. It's definitely hanging inside invoke somewhere. Is this a bug?

    one more clue: There're 100-200 threads calling Method.invoke when the hang happens. The hang is permanent as far as I can tell. I've tried using synchronize in various ways. No luck.

  • Method.invoke

    Hi,
    I'm trying to dynamically load various classes at runtime but have encountered a problem with the Method.invoke() method.
    Class c = Class.forName( "car" );
    Method m = c.getDeclaredMethod("Execute", new Class [] { String.class } );
    object res = m.invoke( Object obj, Object[] arg); // here is the problemI do not know what parameters to set inside Method.invoke(). Looking for some advice here. All the classes that I want to load implement an interface;
    interface loadplugin
       boolean Execute(String str);
    }Any suggestions?

    Hi,
    You put the parameters the Method needs to the Object [] -
    This is a call you know:
    loadplugin myLoadPlugin = new LoadpluginImplementingClass();
    boolean result = myLoadplugin.Execute("Hallo World");The corrsponding call to the Method object is:
    Boolean result = (Boolean)m.invoke(myLoadpugin, new Object[]{"Hallo World"}); The Method object only can hanlde Object types. For any standard data type (int, boolean, double, etc.) the corresponding Wrappers have to be used. So the return in case of the Method-Object call is Boolean, not boolean.
    I hope this helps,
    Lars.

  • How to use java.lang.Class.getMethod() and java.lang.reflect.Method.invoke(

    I want to call a specified method of one class dynamically. I use the method
    "getMethod()" in package "java.lang.Class" to get method and "invoke()" in
    " java.lang.reflect.Method " to invoke method.
    The problem is as following :
    1. There are two argument in this method "getMethod(String MethodName , Class[] paremterTypes)" in package "Class". I have no idea about the second parameter " Class[] parameterTypes ".what does the argument exactly mean ?
    2. There are two argument in the method "invoke(object obj, object[] obj)" in package "Method".
    I have no idea about the second parameter "object[] obj ".what is mean ?
    I pass " null " value to it and it works.But i pass anothers ,jvm will throw exception.

    I have a generic Method Executer that has a method like
    public Object execute(String className, String methodName, Object args)
        String fullClassName = packageName + className ;
        Class delegateClass = Class.forName(fullClassName);
        BaseDelegate delegate = (BaseDelegate)delegateClass.newInstance();
        Method method = null;
        if (args == null)
            method = delegateClass.getMethod(methodName, new Class[] {});
            obj = method.invoke(delegate,new Object[] {});
        else
            method = delegateClass.getMethod(methodName, new Class[] {args.getClass()});
            obj = method.invoke(delegate, new Object[]{args});
       }This seems to have problems when I call the method from a class like:
    execute("CategoryDelegate", "getCategoryById", new Integer(4144));(I get a NoSuchMethodException)
    The method I am trying to execute in CategoryDelegate looks like:
    public Category getCategoryById(int categoryId) throws DelegateExceptionI think it has to deal with the difference in the way we handle Primitive Wrappers and Objects. Wrapper we have to use Interger.TYPE and with the rest of the Objects we have to use obj.class.
    Am I doing something wrong here? Any suggestions to make it work for primitive wrappers as well as Objects?

  • Java.lang.NoSuchMethodException Using Method.invoke(...)

    I try to use Method.invoke() to invoke a method from a class. The method
    has parameters with type JTextArea and JMyFrame, but I got the error
    messages java.lang.NoSuchMethodException . Any ideas???
    If I remove parameter "JFrame mainFrame" in start() method and it is working fine. Not sure why JMyFrame will throw this exception, as JMyFrame is derived from JFrame class
    public class MyFrame extends JFrame
         try
    ClassLoader loader
    = new MyClassLoader(Integer.parseInt("3"));
    Class c = loader.loadClass("NewMenuPackage.NewMenu");
    Class[] params = { JTextArea.class, JMyFrame.class };
         Method m = c.getMethod("start", params);
         Object obj = c.newInstance();
    m.invoke(obj,
         new Object[] {
              textArea,
              JMyFrame.this
    catch (Throwable e)
    JOptionPane.showMessageDialog(this, e);
    package NewMenuPackage;
    import javax.swing.*;
    public class NewMenu
         private static JMenuItem menuItem = new JMenuItem("New Menu");
         public static JMenuItem getJMenuItem()
              return menuItem;
         public static void start(JTextArea textArea, JFrame mainFrame)
              System.out.println("NewMenu->start()...");
    }

    Your "params" Class array has to specify the exact classes of the method, not subclasses. The line that is causing the NoSuchObjectException to be thrown is "c.getMethod("start", params);".
    You have to write your own reflection utility methods to find a method that matches on parameter subclasses.

  • Method.invoke hangs?

    I'm trying to send a Class over a network, then invoke a Method inside the class.
                            final Method command = clazz.getDeclaredMethod("exec");
                            try {
                                System.out.println("Invoked0");
                                command.invoke(null);
                                System.out.println("Invoked1");
                            } catch (Exception e) {
                                throw new RuntimeException(e);
                            }Only Invoked0 prints, and there is no Exception. Whats wrong?
        class CommandClassLoader extends ClassLoader {
            public Class<?> defineClass0(String name, byte[] b, int off, int len) {
                return defineClass(name, b, off, len);
        }

    Oops, didn't realize I was throwing there, its printing a NPE.
    java.lang.NullPointerException
            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:597)
            at colby.client.Client$1$2.run(Client.java:63)
            at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441)
            at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
            at java.util.concurrent.FutureTask.run(FutureTask.java:138)
            at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:98)
            at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:207)
            at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
            at java.lang.Thread.run(Thread.java:619)That doesn't really make sense though? Why would it be happening there?

  • Dynamic casting of Method.invoke() return

    Can anyone clue me in on how to cast the return of Method.invoke() based on Method.getReturnType() or whatever else might work dynamically....that is without knowing which method until runtime?
    Thanks,
    Brad

    Thanks for helping me get a grip....makes perfect sense, I guess I was just wondering how far you could take the runtime decisions thing.
    Can I say that, ( and it seems obvious but... ), programatic flexibility and runtime decision making can only be taken so far - and has to be made in the context of certain presumptions at compike time.
    I can see that in implementing the:
    <jsp: setParameter name="myBean" property="*" />
    Presumptions are made that the values passed to
    the bean setter methods will be String objects and that the
    values returned from the:getter methods using:
    <jsp: getProperty name="myBean" property="whaterver" />
    will also be String objects.
    Reality check?
    Thanks again,
    Brad

  • Using java.lang.reflect.Method.invoke on a static method?

    This is probably a FAQ, but I am finding it impossible to construct a search which answers this question for me.
    How do I call java.lang.reflect.Method.invoke on a static (e.g. class) method? Is it even possible?
    Thanks,
    dwh

    Is this of any help?
    http://www.esus.com/javaindex/j2se/jdk1.2/javalang/reflection/reflection.html
    Cheers,
    Joris

  • Using Reflection - Method.invoke()

    Hi all,
    Facing a problem in using the Reflection API. Can anyone tell me how to use the invoke, which is available with Method. Problem statement. - I want to create a method. And then invoke that method using method1. invoke. But this can take only the following arguments - (Object, Object [ ] ). I cant figure out why I need to pass on an object ? and an array of objects ?

    If you read the docs for Method.invoke, you'll see that the first argument is the object on which you wish to invoke the method, and the second argument is the parameters (with primitives wrapped appropriately).
    foo.bar("abc", 123);
    // becomes
    meth.invoke(foo, new Object[] {"abc", new Integer(123) }); (if I haven't screwed up the syntax of the array initialization)
    http://java.sun.com/docs/books/tutorial/reflect/

  • Is Method.invoke (Object,Class[]) efficient

    hi
    How efficient is the method invoke compared to explicit method calling?
    thanks

    I cna't give any solid numbers either, but when I've used it I've noticed it to be much slower than directly invoking the method. Ballpark I'd guess 5 times as much overhead, but don't hold me to that. Of course, if the work your method does is large compared to method invocation overhead, then it shouldn't really matter.

  • Method.invoke() thread save ?

    Hi to you all,
    Is the method invoke on the Object Method in the java.lang.reflect package threadsafe ?
    Greetz-tbone

    I'have created a with a college a ReflectionMap where getter and setter maps to the javabean properties
    using reflection at creation time the map cache the methods of the underlaying object
    now we want to use it i a multiple thread context
    where more than one thread can access the map a time
    if the implementation of Method is threadsafe then we do not need synchronisation else
    we must synchronize our map.
    and sinds that synchronisation is a performence bottleneck i would like to live it out.
    Tbone

  • Refer to a JTabbedPane from the porgram /&what is the first method invoked?

    Hi there,
    I have been researching for this for a while and couldn?t find the answer, maybe some of you guys can help.
    Situation: I have a program with some JTabbedPane in it
              panel.setLayout(new BorderLayout());
              JTabbedPane pane = new JTabbedPane();
              pane.setTabPlacement(JTabbedPane.LEFT);
              pane.setFont(new Font("Times New Roman", Font.PLAIN, 16));
              pane.add("User", userPanel);
              pane.add("Group Type", groupPanel);
              pane.add("Agent", agentPanel);
              panel.add(pane, BorderLayout.CENTER);
    Question1: sometimes, when the user clicks on JButton, I want to refer him directly to a different ?JTabbedPane?. Meaning, I don?t want him to physically press the ?JTabbedPane? to get there, but I want the program to take him directly to the relevant section. how to do that?
    Quesiotn2: what is the first method invoked when referred to a JTabbedPane. Or, how can I count how many times the users has referred to a particular section.
    Thanks for any help :-)
    dgz

    panel.setLayout(new BorderLayout());
    JTabbedPane pane = new JTabbedPane();
    pane.setTabPlacement(JTabbedPane.LEFT);
    pane.setFont(new Font("Times New Roman", Font.PLAIN,
    16));
    pane.add("User", userPanel);
    pane.add("Group Type", groupPanel);
    pane.add("Agent", agentPanel);
    panel.add(pane, BorderLayout.CENTER);
    Question1: sometimes, when the user clicks on JButton,
    I want to refer him directly to a different
    ?JTabbedPane?. Meaning, I don?t want him to physically
    press the ?JTabbedPane? to get there, but I want the
    program to take him directly to the relevant section.
    how to do that?
    Try this tabPane.setSelectedIndex(anIndex) //eg a number between 0 and tabPane.getTabCount
    Quesiotn2: what is the first method invoked when
    referred to a JTabbedPane. Or, how can I count how
    many times the users has referred to a particular
    section.You can get the component at an index, check if it is showing and update a count variable eg
    Vector counter = new Vector();
    public void checkVisibleTab() {
    for(int x = 0; x < tabPane.getTabCount(); x++) {
       if(tabPane.getComponentAt(x).isShowing())
          counter.addElement( new Integer(x) );
    } You can then iterate through the vector and find how many times a particular number appears and use it for your specific purpose.
    ICE

  • Why PageController method invoked multiple times per request

    I have a page with a customized PageController to override the "prepareModel(LifecycleContext)" method to create bindings dynamically for the page.
    I expected the overridden method only invoked once per loading/refresh of the page.
    From debugging, I found the overridden method actually invoked 3 times before the page was loaded.
    When I put some logic so that bindings only created the 1st time the overridden method invoked, then the page failed to show the data properly as if the binding was missing.
    With some debugging, I noticed the PageController invoked multiple times when I added the af:table to the page.
    Any idea why prepareModel() got invoked multiple time per loading of a page with af:table ?
    How do I determine when to create bindings within prepareModel() so that bindings only created once and the page can use the binding to show the data properly?

    <executables>
    <invokeAction id="onpageLoadClearTable" Binds="clearViewObject"
    RefreshCondition="#{adfFacesContext.postback == false}"/> --------added this into your pagedef.
    </executables>
    <bindings>
    <methodAction IterBinding="XXXXXXXXViewIterator" id="clearViewObject"
    MethodName="clearViewObject" RequiresUpdateModel="true"
    Action="999" IsViewObjectMethod="true"
    </bindings>

  • Refl.Method.invoke(int)

    Hi,
    I would like to invoke a method having primitive int argument through the reflection api.
    Class[] parTypes = new Class[] {int.class};
    Method setIdMethod = myclass.getMethod("setHID", parTypes);
    int cnter = 0;
    Object[] args = new Object[] {cnter}; !!!!!!!!!!!!!! I can not do this!
    setIdMethod.invoke( obj, args);
    The problem, thet the Method.invoce have the obj and Object[] arguments. I can not pass a variable with primitive type.
    Do you know a work-around?
    Thanks,
    Tamas

    To pass primitive values, you have to wrap them in the corresponding Object type.
    E.g. to call a method taking an "int", via reflection, you have to do the actual call as follows:
      setIdMethod.invoke(obj, new Object[]{new Integer(cnter)});

Maybe you are looking for