Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8's missing parameters when using ::

Java 8's :: enables method referencing via method name alone.

protected Object loadBeanController(String url) throws IOException {
    loader = new FXMLLoader(getClass().getResource(url));
    ApplicationContext context = MyProjectClass.getApplicationContext();

    loader.setControllerFactory(context::getBean);

    return loader.getController();
}

But, however, according to BeanFactory Interface (Spring) getBean() getBean does not take empty parameters - Some parameter values are expected:

getBean(String name)
getBean(String name, Class requiredType)
getBean(String name, Object[] args)

How is this resolved?

like image 812
Program-Me-Rev Avatar asked Sep 26 '15 12:09

Program-Me-Rev


People also ask

Should I use optional As parameter?

Java static code analysis: "Optional" should not be used for parameters.

Why optional should not be used for fields?

You should almost never use it as a field of something or a method parameter. So the answer is specific to Optional: it isn't "a general purpose Maybe type"; as such, it is limited, and it may be limited in ways that limit its usefulness as a field type or a parameter type.

What are missing params?

The missing function is used to check the status of the function arguments. It returns a boolean vector that has one element for each argument. If an element of the vector has the value T, it indicates that the corresponding argument is missing and, as a result, is filled in by a default value.


1 Answers

JavaFX's FXMLLoader method setControllerFactory takes a Callback as parameter.

This is a functional interface whose sole method is call taking one parameter and returning one result. In this case, the type of the argument is Callback<Class<?>, Object>. So the lambda expression expects an argument of type Class<?>.

So, actually, none of the methods you cited will be called. What will be called is getBean(Class<T> requiredType) (this method only exists since Spring 3.0 so you won't see it in your linked 2.5.4 reference).

It is possible to rewrite the method expression like this to make this more clear:

loader.setControllerFactory(c -> context.getBean(c));

Here, c will have the type Class<?> because of the declared parameter of setControllerFactory.

As a side note, everything will compile because setControllerFactory expects the result of the callback to be of type Object so the result of context.getBean(c) will always match.

like image 79
Tunaki Avatar answered Sep 17 '22 20:09

Tunaki