OlzD
OlzD

Reputation: 41

Invoking method on all ArrayList<Type> items?

Instead of using foreach externally each time I want to invoke methods on a arraylist I want to be able to call

ArrayList<String>.setText(); //Example.

I attempted this using reflection but I'm not sure how to implement it;

public class Array extends ArrayList
{
    public Array(Collection collection) {
        super(collection);
    }

    public void invokeMethod(String nameOfMethod, Object object)
    {
        for(int index = 0; index < size(); index++){
            get(index).getClass().getMethod(nameOfMethod, object.getClass());
        }

        //Example of a single object invocation.
        try {
            method = obj.getClass().getMethod(methodName, param1.class, param2.class, ..);
        } catch (SecurityException e) {
            // ...
        } catch (NoSuchMethodException e) {
            // ...
        }
    }
}

Does anyone know how to implement this?

Upvotes: 1

Views: 78

Answers (2)

Flown
Flown

Reputation: 11740

You can build your own forEach in pre Java 8. You only need an interface and anonymous classes.

import java.util.ArrayList;
import java.util.List;

public class Test {

    public static void main(String... args) {
        List<MyClass> list = new ArrayList<>();
        for(int i = 0; i < 10; i++) {
            list.add(new MyClass());
        }
        forEach(list, new Consumer<MyClass>() {
            @Override
            public void accept(MyClass t) {
                t.beep();
            }
        });
    }

    public static <T> void forEach(Iterable<T> iterable, Consumer<T> consumer) {
        for (T t : iterable) {
            consumer.accept(t);
        }
    }
}

interface Consumer<T> {
    void accept(T t);
}

class MyClass {

    public void beep() {
        System.out.println("beep");
    }
}

Upvotes: 0

Eran
Eran

Reputation: 393956

Java 8 already offers this kind of functionality, so there's no point in trying to implement it by yourself.

For example :

ArrayList<SomeClass> list = ...;
list.forEach(o -> o.SomeMethod());

or

list.forEach(SomeClass::SomeMethod);

Upvotes: 3

Related Questions