问题
So Java 8 introduces method references and the docs describe the four types.
My question is what\'s the difference between the two instance types?
- Reference to an instance method of a particular object.
- Reference to an instance method of an arbitrary object of a particular type.
Both refer to references but what\'s significantly different? Is it that the type inference used to resolve them is different? Is it significant that (in their examples) one is a closure and the other is a lambda? Is it something to do with the number of arguments on a method?
回答1:
1) myString::charAt
would take an int
and return a char
, and might be used for any lambda that works that way. It translates, essentially, to index -> myString.charAt(index)
.
2) String::length
would take a String
and return an int
. It translates, essentially, to string -> string.length()
.
I'm not even sure if String::charAt
would translate to (string, index) -> string.charAt(index)
. I'd kind of expect it to, though.
回答2:
With this they mean that you have the following:
1) Can be for example this::someFunction;
, this will return the someFunction
reference of the current object.
2) Can be for example String::toUpperCase
, this will return the toUpperCase
method of String
in general.
I am not sure if there is an actual difference in behaviour, I think it is just like you can also call static methods on instance variables.
来源:https://stackoverflow.com/questions/22516331/whats-the-difference-between-instance-method-reference-types-in-java-8