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 methodName
).
Then you invoke that method by calling
try {
method.invoke(obj, arg1, arg2,...);
} catch (IllegalArgumentException e) { ... }
catch (IllegalAccessException e) { ... }
catch (InvocationTargetException e) { ... }
Again, leave out the arguments in .invoke
, if you don't have any. But yeah. Read about Java Reflection
How to call a method by name (String) in Java?
You cannot. Java doesn't treat functions as first class objects, because it doesn't have functional features like Python or C#.
You can create a Command interface and pass that object reference:
public interface Command {
void execute(Object [] args);
}
How to call method by Name from variable value in perl?
This is not really recommended because there are safety issues, but you can use the name of a subroutine to call it:
my $method = "hello";
{
no strict 'refs';
&{$method}(); # same as hello()
}
This &{...}()
syntax “dereferences” the subroutine name and calls it.
If you're calling methods on an object, you can skip the no strict 'refs'
part:
my $method = 'name';
$object->$method(); # same as $object->name
If you only want to allow a couple of subroutines, it would be much better to store them in a hash table:
my %known_functions = (
hello => \&hello, # \& stores a reference to a subroutine
bye => \¬_hello, # added benefit: renaming them
);
# define the functions somewhere
sub hello { ... }
sub not_hello { ... }
# can't access secret methods unless they are added to the hash table
sub secret { ... }
# use a hash lookup and call the method
my $method = 'hello';
$known_functions{$method}();
How to call method by name using Kotlin Reflection?
try this:
obj::class.members.firstOrNull { it.name == "methodName" }?.call(argument1, argument2, ...)
Call a Python method by name
Use the built-in getattr()
function:
class Foo:
def bar1(self):
print(1)
def bar2(self):
print(2)
def call_method(o, name):
return getattr(o, name)()
f = Foo()
call_method(f, "bar1") # prints 1
You can also use setattr()
for setting class attributes by names.
Retrieving the calling method name from within a method
I don't think it can be done without tracing the stack. However, it's fairly simple to do that:
StackTrace stackTrace = new StackTrace();
MethodBase methodBase = stackTrace.GetFrame(1).GetMethod();
Console.WriteLine(methodBase.Name); // e.g.
However, I think you really have to stop and ask yourself if this is necessary.
Calling a function of a module by using its name (a string)
Given a module foo
with method bar
:
import foo
bar = getattr(foo, 'bar')
result = bar()
getattr
can similarly be used on class instance bound methods, module-level methods, class methods... the list goes on.
Related Topics
How to Fix in Ruby on Rails the Undefined Method 'Alias_Method_Chain' Error
Bundle Install Is Using a Different Ruby Version
Error While Installing Iconv on Windows by Ruby2.0.0
Regex Negative Lookbehind in Ruby Doesn't Seem to Work
Execute Code Once Sinatra Server Is Running
Ruby on Rails Workflow Engine (Like Ibm Workflow)
Rails Cannot Find Model with Same Name as Ruby Class
How to Serialize as Activesupport::Hashwithindifferentaccess Anymore
Passing Variables on the Command Line to a Cucumber Test
While Executing Gem ... (Argumenterror) Unknown Encoding Name - Cp720
How to Make Empty Tags Self-Closing with Nokogiri
Access 'Self' of an Object Through the Parameters
Working with Multiple Processes in Ruby
Rails Not Working for New Project. Showingerror " Superclass Mismatch for Class Cipher (Typeerror)"
Gem Install Debugger -V '1.5.0' Fails
Openssl::Cipher::Ciphererror When Running Staging Db on Local