The problem in your last snippet is that there is no way for the compiler to guess that
() -> {
// code omitted
return null;
}
is a lambda expression that implements the SAM of the Supplier
interface (and it seems you missed parentheses around the expression in the first place, but anyway).
The thing you could do is to cast the lambda in order to tell the compiler that this is actually the abstract method of the Supplier
interface that you implement:
private ConnectionFactory connectionFactory =
((Supplier<ConnectionFactory>)() -> {
// code omitted
return null;
}).get();
But then what do you gain with that instead of having an initializer
private ConnectionFactory connectionFactory;
{
//code omitted
connectionFactory = null;
}
or initialize the connection within the constructor or with a final method:
private ConnectionFactory connectionFactory = initConnection();
private final ConnectionFactory initConnection() {
//code omitted
return null;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…