John Smith
John Smith

Reputation: 6197

Java, return method as reference

Im beginner JAVA developer. Here is a method:

private Method getSomething()
{
    for (Method m : getClass().getDeclaredMethods())
    {
        return m;
    }
    return notFound;
}

private void notFound()
{
    throw new Exception();
}

it doesnt matter what it does - if it finds something, then returns a Method - if not, the notFound() method itself should be returned. So the hot spot is at the return notFound; line: if I use return notFound(); then it returns its value, not the method itself. I want something like a reference/pointer. So getSomething() returns something what can be called, and if the returned method is used wrong, it should trigger that Exception - so its not an option to replace return notFound; with throw new Exception(); ! Or the 2nd option is to create a lambda method....

Upvotes: 4

Views: 199

Answers (2)

peter.petrov
peter.petrov

Reputation: 39457

You need to call

this.getClass().getMethod("notFound")

to get the notFound method of the current/this object's class.

So just do this:

return this.getClass().getMethod("notFound");

More details here:

Class.getMethod

EDIT:

You can retrieve i.e. get and call private methods too via reflection.

Here is an example.

import java.lang.reflect.Method;


public class Test001 {

    public static void main(String[] args) throws Exception {
        Test002 obj = new Test002();
        Method m = obj.getClass().getDeclaredMethod("testMethod", int.class);
        m.setAccessible(true);

        m.invoke(obj, 10);
        m.invoke(obj, 20);

        System.out.println(m.getName());
    }


}

class Test002 {
    private void testMethod(int x){
        System.out.println("Hello there: " + x);
    }       
}

Upvotes: 8

czupe
czupe

Reputation: 4919

You need to use reflection to achieve this:

http://docs.oracle.com/javase/tutorial/reflect/

e.g. to get all methods of a given class:

Class aClass = ...//obtain class object
Method[] methods = aClass.getMethods();

Upvotes: 2

Related Questions