How to call a method stored in a HashMap? (Java) [duplicate]

With Java 8+ and Lambda expressions With lambdas (available in Java 8+) we can do it as follows: class Test { public static void main(String[] args) throws Exception { Map<Character, Runnable> commands = new HashMap<>(); // Populate commands map commands.put(‘h’, () -> System.out.println(“Help”)); commands.put(‘t’, () -> System.out.println(“Teleport”)); // Invoke some command char cmd = ‘t’; … Read more

What could cause java.lang.reflect.InvocationTargetException?

You’ve added an extra level of abstraction by calling the method with reflection. The reflection layer wraps any exception in an InvocationTargetException, which lets you tell the difference between an exception actually caused by a failure in the reflection call (maybe your argument list wasn’t valid, for example) and a failure within the method called. … Read more

Invoke(Delegate)

The answer to this question lies in how C# Controls work Controls in Windows Forms are bound to a specific thread and are not thread safe. Therefore, if you are calling a control’s method from a different thread, you must use one of the control’s invoke methods to marshal the call to the proper thread. … Read more

Cross-thread operation not valid: Control ‘textBox1’ accessed from a thread other than the thread it was created on [duplicate]

The data received in your serialPort1_DataReceived method is coming from another thread context than the UI thread, and that’s the reason you see this error. To remedy this, you will have to use a dispatcher as descibed in the MSDN article: How to: Make Thread-Safe Calls to Windows Forms Controls So instead of setting the … Read more

What’s the difference between Invoke() and BeginInvoke()

Do you mean Delegate.Invoke/BeginInvoke or Control.Invoke/BeginInvoke? Delegate.Invoke: Executes synchronously, on the same thread. Delegate.BeginInvoke: Executes asynchronously, on a threadpool thread. Control.Invoke: Executes on the UI thread, but calling thread waits for completion before continuing. Control.BeginInvoke: Executes on the UI thread, and calling thread doesn’t wait for completion. Tim’s answer mentions when you might want to … Read more

How do I invoke a Java method when given the method name as a string?

Coding from the hip, it would be something like: java.lang.reflect.Method method; try { method = obj.getClass().getMethod(methodName, param1.class, param2.class, ..); } catch (SecurityException e) { … } catch (NoSuchMethodException e) { … } The parameters identify the very specific method you need (if there are several overloaded available, if the method has no arguments, only give … Read more