Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, return method as reference

Tags:

java

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....

like image 515
John Smith Avatar asked Dec 26 '22 06:12

John Smith


1 Answers

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);
    }       
}
like image 150
peter.petrov Avatar answered Dec 28 '22 06:12

peter.petrov