假设我有以下代码:
Runnable exceptionHandler = () -> throw new RuntimeException();
Run Code Online (Sandbox Code Playgroud)
有没有办法让它更简洁,现在可用,或者在将来的Java版本中可用?我期待的是:
Runnable exceptionHandler = RuntimeException::throw;
Run Code Online (Sandbox Code Playgroud)
有关额外信息,我打算将此代码用于可能发生异常情况的方法,但并不总是需要RuntimeException抛出.在特殊情况发生时,我想让呼叫者自由地做任何他们想做的事情.
在我看来,Java 8是不可能的,这已经讨论过了,有什么理由不可能吗?
假设我想将java方法分配给方法类型Log.d(String, String)的变量x,(String, String) -> Int我这样做:
val x: (String, String) -> Int = android.util.Log::d
Run Code Online (Sandbox Code Playgroud)
编译器说:
Error:(50, 56) Overload resolution ambiguity:
public open fun d(tag: kotlin.String!, msg: kotlin.String!): kotlin.Int defined in android.util.Log
public open fun d(tag: kotlin.String!, msg: kotlin.String!, tr: kotlin.Throwable!): kotlin.Int defined in android.util.Log
Run Code Online (Sandbox Code Playgroud)
显然还有第二种方法Log.d(String, String, Throwable)但是如何告诉编译器我想要哪一种?
假设我有一些像Function这样的函数接口和一些不同类的方法,我可以为它们提供方法引用,例如:
class A {
public int getPrimitive() { return 0; }
public Integer getBoxed() { return 0; }
public static int getStaticPrimitive(A a) { return 1; }
}
Function<A, Integer> primitive = A::getPrimitive;
Function<A, Integer> boxed = A::getBoxed;
Function<A, Integer> staticPrimitive = A::getStaticPrimitive;
Run Code Online (Sandbox Code Playgroud)
我如何通过反射获取从A类转换为Function接口实例的所有可能的方法引用?
到目前为止,这个问题与评论中提到的任何问题都不重复,但多亏了Holger在评论中提到的两个问题,我已经设法做了我需要的事情:
class Test {
public static void main(String[] args) throws Throwable {
HashMap<String, Function<A, Integer>> map = new HashMap<>();
Collection<MethodType> supportedTypes = Arrays.asList(
MethodType.methodType(int.class, A.class),
MethodType.methodType(Integer.class, A.class)
);
MethodType inT = MethodType.methodType(Function.class);
MethodHandles.Lookup …Run Code Online (Sandbox Code Playgroud) 当我想引用当前作用域中的方法时,我仍然需要指定类名(对于静态方法)或者this在::
操作符之前.例如,我需要写:
import java.util.stream.Stream;
public class StreamTest {
public static int trimmedLength(String s) {
return s.trim().length();
}
public static void main(String[] args) {
System.out.println(Stream.of(" aaa ", " bb ", " c ")
.mapToInt(StreamTest::trimmedLength).sum());
}
}
Run Code Online (Sandbox Code Playgroud)
这不是一个大问题this,但有时看起来过于拥挤静态方法,因为类名可能很长.如果编译器允许我简单地编写它会很好::trimmedLength:
public static void main(String[] args) {
System.out.println(Stream.of(" aaa ", " bb ", " c ")
.mapToInt(::trimmedLength).sum());
}
Run Code Online (Sandbox Code Playgroud)
但是Java-8编译器不允许这样做.对我来说,如果类/对象名称的解析方式与普通方法调用相同,那么它似乎会非常一致.这也将支持方法引用的静态导入,这在某些情况下也很有用.
所以问题是为什么在Java 8中没有实现这样或类似的语法?这种语法会出现什么问题吗?或者根本不考虑它?
假设我有一个名为 的类Server,我想让其他Plugins人为它编写代码。SayPlugin是一个接口,它扩展Runnable并添加了一个方法:void init(...). 插件的工作是收集数据并将其发送到服务器。然而,当需要向服务器发送数据时,它是如何做到的呢?来自 C 和 C++ 我正在寻找沿着函数指针的思路。尽管我没有在 Java 标准类库之外找到示例,但在 Java 中似乎是可能的。
我如何将方法引用传递给init方法,以便它可以由 存储Plugin,然后我如何在插件想要发送数据时调用该方法?现在说所需的 Server 方法是:void sendData(Integer data)。
例如:
// Inside Server
Plugin p = new PluginImplementation();
p.init(this::sendData);
// Plugin init
public void init(?? sendMethod) {
storedSendMethod = sendMethod;
// ...
}
// Plugin run
public void run() {
// ...
storedSendMethod(x) // Sends data to server
// ...
}
Run Code Online (Sandbox Code Playgroud) 演示失败的示例代码:
package ia.quant.nextgen.entry;
import com.google.common.collect.ArrayListMultimap;
import java.util.function.Consumer;
/**
* Created by arpeke on 2015-12-18.
*/
public final class SampleMain {
public static void main(String[] argArr) {
final ArrayListMultimap<Void, Void> arrayListMultimap = ArrayListMultimap.create();
arrayListMultimap.clear();
final Consumer<ArrayListMultimap> arrayListMultimapConsumer = ArrayListMultimap::clear;
arrayListMultimapConsumer.accept(arrayListMultimap);
}
}
Run Code Online (Sandbox Code Playgroud)
这是Error(不Exception)我看到的:
Exception in thread "main" java.lang.IllegalAccessError:
tried to access class com.google.common.collect.AbstractMapBasedMultimap
from class ia.quant.nextgen.entry.SampleMain
at ia.quant.nextgen.entry.SampleMain.lambda$main$1(SampleMain.java:17)
at ia.quant.nextgen.entry.SampleMain.main(SampleMain.java:18)
Run Code Online (Sandbox Code Playgroud)
我使用的是32位Java 8(v1.8.0_60)和Google Guava v19.0.我的Google-Fu告诉我Google Guice是根本原因,但缺乏可信的解释.(这是一个更大的项目的一部分,该项目还包括通过Apache Maven的Google Guice v3.0.)
示例参考:https://github.com/hierynomus/scannit/issues/7
有人知道吗...?
(最后,我也试过Google Guava …
我注意到如果我写的东西如下:
View view = getView();
foo(error -> view.showError(error));
Run Code Online (Sandbox Code Playgroud)
Android Studio(也可能是IntelliJ)显示"可以用方法引用替换"的建议.
相反,如果我写
foo(error -> getView().showError(error));
Run Code Online (Sandbox Code Playgroud)
Android Studio没有说什么.
但在这两种情况下我都可以使用方法引用:
foo(view::showError)
Run Code Online (Sandbox Code Playgroud)
和
foo(getView()::showError)
Run Code Online (Sandbox Code Playgroud)
, 分别.
这两种形式在功能上是不同的吗?他们似乎做了同样的事情,但Android Studio似乎不同意.
有很多问题让人们意识到用一个表达式来计算一个null值来创建一个方法引用会产生一个NullPointerException.举个例子:
String s = null;
Supplier<char[]> fun = s::toCharArray;
Run Code Online (Sandbox Code Playgroud)
这是由于java规范中的以下段落:
首先,如果方法引用表达式以ExpressionName或Primary开头,则计算此子表达式.如果子表达式的计算结果为null,则会引发NullPointerException,并且方法引用表达式会突然完成.如果子表达式突然完成,则方法引用表达式会出于同样的原因突然完成.
现在我的问题是,有没有人碰巧知道背后的原因(基于许多困惑的问题)反直觉规范是什么?
我唯一想到的是,在以下情况下,很难准确地报告NullPointerException在评估期间发生的错误Supplier:
public static char[] callback(Supplier<char[]> supplier) {
return supplier.get();
}
public static void main(String[] args) {
String s = null;
callback(s::toCharArray);
}
Run Code Online (Sandbox Code Playgroud) 我是Java 8的新手,具有以下表达式:
.map(mc -> mc.getName().getDefaultName())
Run Code Online (Sandbox Code Playgroud)
我想知道是否可以将其替换为:
.map(TeleBadalonaCampaignType::getName::getDefaultName)
Run Code Online (Sandbox Code Playgroud) 给出以下代码
List<Person> persons = ..;
List<Person> personsWithoutAddress =
persons.stream().filter(p -> p.getAddress() == null)
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
有没有一种方法可以Person::getAddress在过滤器中内联使用方法引用(可能与Objects::isNull某些 Guava 实用程序方法结合使用...),而无需编写额外的实用程序方法/谓词?
method-reference ×10
java ×9
java-8 ×7
guava ×2
lambda ×2
exception ×1
java-stream ×1
kotlin ×1
reflection ×1