1

Is it posible in java?

void aaa(){}

ArrayList<Method> list = new ArrayList<Method>();
list.add(aaa);

If it isn't, how i can realize collection of methods (functions).
I want to get some method by ID.

3
  • Look into Command pattern and then reflection. Commented Oct 11, 2013 at 16:01
  • @SotiriosDelimanolis why command pattern? Commented Oct 11, 2013 at 16:02
  • @nachokk It's a good pattern for implementing function pointers. Commented Oct 11, 2013 at 16:03

4 Answers 4

4

You can do something like:

interface VoidFunction {
    void evaluate();
}

...

List<VoidFunction> list = new ArrayList<>();

VoidFunction aaa = new VoidFunction() {
    @Override
    public void evaluate() {
        aaa();
    }
}

list.add(aaa);

In Java 8 this should be much easier and nicer:

List<Consumer<Void>> list = new ArrayList<>();

Consumer<Void> aaa = () -> {...};

list.add(aaa);

(I believe I have the syntax right)

If you already have the aaa method defined as a regular method, you'll be able to do something like:

list.add(MyClass::aaa);
Sign up to request clarification or add additional context in comments.

5 Comments

Grats on 40k. Also, this solution is cleaner than Reflection.
I need it for android (unfortunately Java 7)
@Vladimir You can always use the first approach.
ty, and how I can call some method from List? //list.get(0); and it will start aaa() ??
@Vladimir list.get(0).evaluate(). You can change the name to whatever you want by changing the method in the interface, but with the snippet above that will work.
2

You need to use reflection to get the Method, e.g.

this.getClass().getMethod("aaa")

Alternatively, if you don't need to access methods defined on a class, you can use Callables.

ArrayList<Callable> list = new ArrayList<Callable>();
list.add(new Callable() {
   public String call() {
     return "asdf";
   }
});

Comments

0

I believe you can do it, but you need to use reflection to get the methods from a class/object. Maybe this links helps: http://tutorials.jenkov.com/java-reflection/methods.html

The way you have done it does not work.

Comments

0

You can call following method of Class

public Method[] getMethods() throws SecurityException

Returns an array containing Method objects reflecting all the public member methods of the class or interface represented by this Class object, including those declared by the class or interface and those inherited from superclasses and superinterfaces.

public Method[] getDeclaredMethods() throws SecurityException

Returns an array of Method objects reflecting all the methods declared by the class or interface represented by this Class object. This includes public, protected, default (package) access, and private methods, but excludes inherited methods.

Read more here

Cheers !!

Comments

Your Answer

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