Invoking a method by its name [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I invoke a Java method when given the method name as a string?
I have 10 methods named: m1, m2, m3,...
like this:
public void m1(){
..
}
How do I invoke them with string in a 'for' loop?
I want to do this:
for (int i=1;i<11;i++){
invoke('m'+i);
}

You need to use reflection to achieve this.
Method method = getClass().getMethod(methodName);
method.invoke(this);
So, you need to store your method names in an array and use this code piece to call those methods one by one.

You can do this with reflection.
However, I would be interested in your use case. Often it is possible to refactor an application, so that the use of reflection is superfluous.

Use java reflection on this object.

Related

What is a method signature? [duplicate]

This question already has answers here:
Definition of a method signature?
(7 answers)
Closed 7 years ago.
I read a book titled 'Object First with Java' and in page 7 the author mentioned that the method signature "provides information needed to invoke that method". And the the author gave the following example:
void moveHorizontal(int distance)
However, today when I was watching a video about C# on Pluralsight, the author said that "the return type of a method is not part of the method signature".
I'm confused now and would like know what is a method signature?
A method-signature is the part of the method based on which you overload / override it. It contains :
The method name.
The arguments passed to it.
It doesn't contain :
Scope / access modifier
return type.
Method signature is used in interfaces and in abstract classes, but we always define the method data type(return type). It will be something invaluable if the return type is not a part of the signature.

Invoking the caller of a method in Java [duplicate]

This question already has answers here:
How do I find the caller of a method using stacktrace or reflection?
(13 answers)
Closed 9 years ago.
Just wondering, how do you find out the name of the method that invokes another method? I want to use the Method class.
You can make use of StackTraceElement :
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
Order of elements in StackTraceElement array: The last element of the array represents the bottom of the stack, which is the least recent method invocation in the sequence.
Once you have the desired method name then you can call it using reflection :
Method lastMethod = YourClass.class.getMethod("yourMethodName");
lastMethod.invoke();
Note: The code should be changed as per your class and method.
Getting the name is tricky enough, getting the method is very hard because you don't know the argument list but you do know the class and you can use the line number when reading the byte code to find which method which contains that line. If the method is static (and I suspect its not) you are ok. If you need an instance, finding that is next to impossible in any portable way.
The sort of thing you are trying to do is the Java equivalent of saying; how do I learn to flight in a couple of easy steps.
What ever your problem is this is highly unlikely to be a good solution. If you need to call back to the object which called you, you should pass that object as an argument, ideally via an interface.
When ever you find the code running back on itself, this is sure to end in a mess of some kind, You want to simplify your dependencies.
What you should do is something like this.
interface Callback<T> {
onResult(T t);
}
class A implements Callback<MyResult> {
B b = new B();
public void method() {
b.doSomething(this);
}
public void onResult(MyResult mr) {
// do something with mr
}
}
class B {
public void doSomething(Callback<MyResult> cb) {
// do something
cb.onResult(new MyResult(something));
// do something else
}
}
Of course this would be all much simpler if instead of call back on the first method, you just returned a result and half this code wouldn't be needed. This is why normally when you want to pass something back to the caller, you use a return value instead of recursion.

Something like "typedef" for Java's EnumSet [duplicate]

This question already has answers here:
Is there a Java equivalent or methodology for the typedef keyword in C++?
(12 answers)
Closed 9 years ago.
I'm using EnumSet<Foo> in multiple places. I'd like to create a EnumSetFoo class so I could do EnumSetFoo xyz = EnumSet.of(Foo.BAR), but subclassing EnumSet doesn't seem to be the way to go. Is there a way of achieving this effect in Java?
Java doesn't have typedefs, but EnumSet.of() returns a typed EnumSet, and you shouldn't need anything more.
You don't need to cast it to anything to use what's returned:
EnumSst<Foo> e = EnumSet.of(Foo.BAR);
If you really want to use your own class, provide an appropriate constructor and pass the above to it or pass instances of the enum in to a typed varargs constructor:
public class EnumSetFoo extends EnumSet<Foo> {
public EnumSetFoo(Foo... foos) {
addAll(Arrays.asList(foos));
}
}
or whatever.

How does a method signature of only "static" work? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Static initializer in Java
I have a few years' experience with Java, but I've recently run across something I've never seen before:
public class Project{
...
static{
initDataTypeMapping();
}
...
}
How does this method signature work? Is this in fact even technically a method? I'm wondering why one wouldn't simply put the the method call to initDataTypeMapping() in the constructor. Just trying to increase my understanding so I don't mess something up. Thanks!
This is known as a static initializer.
The code in the static { } block is run when the class is first loaded by the classloader (which is usually, but not always, when code that refers to the class is first loaded/executed), and is guaranteed to be run in a thread-safe manner.
See this question also.

How to call Java function from string stored in a Variable [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Calling a method named “string” at runtime in Java and C
I need to be able to call a function, but the function name is stored in a variable, is this possible. e.g:
public void foo ()
{
//code here
}
public void bar ()
{
//code here
}
String functionName = "foo";
// i need to call the function based on what is functionName
Anyhelp would be great, thanks
Yes, you can, using reflection. However, consider also Effective Java 2nd Edition, Item 53: Prefer interfaces to reflection. If at all possible, use interfaces instead. Reflection is rarely truly needed in general application code.
See also
Java Tutorials/Reflection API
Java Advanced Language Topics/Reflection
Related questions
Calling a method named “string” at runtime in Java and C
Easily done with reflection. Some examples here and here.
The main bits of code being
String aMethod = "myMethod";
Object iClass = thisClass.newInstance();
// get the method
Method thisMethod = thisClass.getDeclaredMethod(aMethod, params);
// call the method
thisMethod.invoke(iClass, paramsObj);
Use reflection.
Here's an example
With the reflection API. Something like this:
Method method = getClass().getDeclaredMethod(functionName);
method.invoke(this);

Categories