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)});
Similar Messages
-
Using Java Reflection to call a method with int parameter
Hi,
Could someone please tell me how can i use the invoke() of the Method class to call an method wiht int parameter? The invoke() takes an array of Object, but I need to pass in an array of int.
For example I have a setI(int i) in my class.
Class[] INT_PARAMETER_TYPES = new Class[] {Integer.TYPE };
Method method = targetClass.getMethod(methodName, INT_PARAMETER_TYPES);
Object[] args = new Object[] {4}; // won't work, type mismatch
int[] args = new int[] {4}; // won't work, type mismatch
method.invoke(target, args);
thanks for any help.Object[] args = new Object[] {4}; // won't work, type
mismatchShould be:
Object[] args = new Object[] { new Integer(4) };The relevant part of the JavaDoc for Method.invoke(): "If the corresponding formal parameter has a primitive type, an unwrapping conversion is attempted to convert the object value to a value of a primitive type. If this attempt fails, the invocation throws an IllegalArgumentException. "
I suppose you could pass in any Number (eg, Double instead of Integer), but that's just speculation. -
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? -
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. -
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 :-)
dgzpanel.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 -
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? -
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?
ThanksWhat 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 -
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. 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.
-
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,
BradThanks 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 -
GregorianCalendar method add(int,int) in websphere5.1
This bug report landed in my lap. The program is registering payments, and when user is registering multiple payments he gets the duedate set to 1970 from the second payment and on. Someone wrote on the bug report "method add(int,int) in GregorianCalendar doesn't work in WebSphere 5.1".
So, when t>0 in the following code, things go haywire. Anyone have experience with this?
dueDateG.clear();
dueDateG.setLenient(false);
dueDateG.setTime(dueDate);
if (t==0) addMonth = 0;
else addMonth = freq;
dueDateG.add(Calendar.MONTH, addMonth);
date = dueDateG.getTime();
dueDate = date;By "Websphere 5.1" are you meaning Websphere Application Server 5.1 or Websphere Application Developer 5.1?
The former (as known as WAS) uses IBM JDK 1.4.X (I believe that's 1.4.1); the later (as known as WSAD) can be used with any version of WAS starting from 4.X I believe.
Some things can have problems when you're using IBM JDK's instead of Sun's, for instance trying to use the javax.crypto.* classes, that are different from Sun's; but I don't know if GregorianCalendar has problems. The first thing to do is insulate the code that you sent and try running it in IBM's and Sun's JDK. If you get problems only with IBM's JDK, you'll need to rewrite your code. -
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,
dwhIs 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?
thanksI 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-tboneI'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
Maybe you are looking for
-
Multiple measurement types, help!
I am trying to write a multi-purpose vi for students to use for acquiring and recording strain, thermocouple, LVDT, and DC voltage signals as needed by their experiments. We have a setup on wheels with a PCI-6052E card cabled to an SCXI 1001 chassis
-
Question on seeburger mappings
Iam going to work on seeburger, at the moment we have installed seeburger on PI7.11 We have some vendors who woukd initiate the EDI transactions, we would be getting a request in EDI format for wchch we need to respond back. I have a little ide that
-
How can I get my 6700 classic to use 3g?
I am told this phone should be working on the new 3g network & a symbol should show on the phone? Ive never seen the symbol. Is there any way to check if it is indeed on 3g?
-
Collaboration Launch Pad permissions
hi... 1)how to assign the CLP(Collaboration launch pad) permission or access to particular group or users? 2)what role needs to be assigned to the group enable CLP(Collaboration launch pad)
-
With_item linking with fi tables
Hi guys, I am carrying out a requiremnt for Brazil. I need to print base, rate , tax code and amount all of which have nine types viz inss,ir,pis,confis,csll,iss,funrural,sest,senat. Now as far as I understand I will have to read bseg with belnr gjah