hellzone
hellzone

Reputation: 5246

How to create a Java Function list?

I want to create a list from Java Functions. But When I try to add a function to functions list, it says;

Non-static variable cannot be referenced from a static context

I don't get which method is static. Is there any idea?

My Main class:

public void createFunctionList() {
    List<Function> functions = new ArrayList<>();
    functions.add(Product::getInfo);
}

My product class:

public class Product 
{
    public Info getInfo() {
        return info;
    }
}

Upvotes: 3

Views: 2860

Answers (1)

Eran
Eran

Reputation: 394146

Product::getInfo can be assigned to a Function<Product,Info> (since it's a non-static method, so it can be seen as a function that takes a Product instance and returns an Info instance). Change the declaration of functions from

List<Function> functions = new ArrayList<>();

to

List<Function<Product,Info>> functions = new ArrayList<>();

EDIT: I tested your code, and I get a different compilation error:

The type Product does not define getInfo(Object) that is applicable here.

The compilation error you got is misleading. Once I make the suggested change, the error goes away.

Upvotes: 3

Related Questions