0

I know how to invoke a method by reflection, it creates a new instance. But I can't do that. Because my class impelemented Runnable interface, I have to start run method in a new thread. So this is not desired. My code now is:

public class Validation () impelements Runnable {
  Validation (String[] methodName) {
    if(methodName[2].equals("deposit") ){
        this.deposit(account);
    }
    else if (methodName[2].equals("withdraw") ){
        this.withdraw(account);
    } 
    // lots of if-else
}
//..... other methods , deposit() , withdraw() , run();
}

I need something like this (without creating a new instance of class but it should be reflection) :

UPDATE :

if-else should replace with something like this:

try {
this.invoke(methodName[2] , account);
} catch (Exceotion ex){
 // something
}

I can't use static deposit or withdraw methods, they are using non-static variables.

In php we have simething like this:

$methodName = $array[2] ;
$this.methodName();

My question is :

How to invoke a non-static method by reflection without creating new instance in same class?

5
  • 1
    You cannot. It's impossible. You need an instance to invoke instance methods. Commented Apr 15, 2016 at 5:44
  • 2
    You can't do that. Just think about it - how can you invoke an object method (which can modify its state) without the object? Commented Apr 15, 2016 at 5:44
  • Are you asking how to invoke a method by reflection on an existing object? Commented Apr 15, 2016 at 5:46
  • 2
    I don't understand your question. You say "I know how to invoke a method by reflection", which works just fine with an already existing object. There's no need to "create a new object". Commented Apr 15, 2016 at 5:50
  • @JimGarrison please see again, I've changed something Commented Apr 15, 2016 at 5:59

2 Answers 2

1

This is not possible.

Just think about it, non-static methods are linked with objects of the class, rather then with the class itself.

So, to invoke them you need instance of class.

It would be another matter though, if you want to invoke a non-static method with reflection, but without instantiating, it is not possible.

Sign up to request clarification or add additional context in comments.

Comments

1

Exception handling omitted for clarity

class ObjectThatImplementsFoo {
    public void foo() {
    }
}

public void invokeFooOnObject(ObjectThatImplementsFoo foo) {
   Method m = foo.getClass().getMethod("foo");
   m.invoke(foo, null);
}

So your "if-else" should be replaced with something more like this:

try {
    Method m = this.getClass().getMethod(methodName[2], account.getClass());
    m.invoke(this, account);
} catch (Exception ex){
 // something
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.