Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closure in Java or something like it

I have been trying to find a way to incorporate something similar to Closure in Java 1.6 since I'm developing for Android.

What I want (in a perfect world) I have a class, we will call it "Item".

I then have an arrayList of these.

ArrayList<Item> items = new ArrayList<item>;

In each one of them items.get(x) I want to save a block of code that will be executed when called. This block of code needs to take place in the scope of the class housing the ArrayList items.

My only, half brained idea, would be to create the methods in the class that housed "items" and save the name of the function in each of the "item" instances, then use reflection to call those methods....

I'm pretty doubtful that this could be possible, but this is the place I will find an answer either way.

Thanks ahead of time for any help.

like image 526
JoeyG Avatar asked Dec 22 '22 01:12

JoeyG


1 Answers

What you need is an interface like

interface Closure{
    public void exec();
}

and create an anonymous class for each "closure" code you want

Closure closure = new Closure() {
    public void exec(){
        // code here
    }
}
like image 142
Chikei Avatar answered Jan 05 '23 18:01

Chikei