3

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;
    }
}
2
  • 3
    When you do Product::getInfo you make a reference to the function getInfo in the class Product. And thus without using an instance. So java is expecting getInfo to be static Commented Mar 20, 2018 at 10:32
  • Do you mean a Java Function or the Method of a Class? Commented Mar 20, 2018 at 10:35

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

6 Comments

I don't think this solves the problem. getInfo should be static to be referenced with Product::getinfo
@Héctor method references can refer to non static methods. A static method wouldn't fit the Function interface, since it would have a return type but no input argument.
Of course, but a this reference is needed, when it's not static.
@Héctor it's not needed. this is only needed if you want the method reference to refer to a specific instance of the class.
@hellzone do you want a List<Function<Object,Object>>? That's not type safe. Each function expects a specific type of input and produces a specific type of output. If you do use a List<Function<Object,Object>>, you can add functions to it such as functions.add(p -> ((Product)p).getInfo());, but that casting is not safe.
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.