【问题标题】:Is there a difference between these lines of code [duplicate]这些代码行之间是否有区别[重复]
【发布时间】:2018-09-17 06:10:12
【问题描述】:

这些代码行之间有区别吗?最好用什么? 谢谢

public static void main( String[] args ){
   SwingUtilities.invokeLater( () -> component.method() ); }

public static void main( String[] args ) {
   SwingUtilities.invokeLater( new Runnable() {
      public void run(){
            component.method();
    }} );
}

public static void main( String[] args ) {
   SwingUtilities.invokeLater( new Runnable() {
      public void run(){
            component::method();
    }} );
}

【问题讨论】:

  • 第三个不会编译。
  • 有区别,是的。但是最后一个不会编译(应该是invokeLater(component::method);
  • 前两个读这个:alvinalexander.com/java/… 最后一个读这个:stackoverflow.com/questions/20001427/…
  • 在 lambda 函数内部的方法调用和直接方法引用之间的唯一区别是 StackTrace 中多了一行。

标签: java lambda


【解决方案1】:

最后一个没有通过编译。

使用任一 lambda 表达式

SwingUtilities.invokeLater(() -> component.method());

或方法参考

SwingUtilities.invokeLater(component::method);

比第二个短,这使得它们在 Java 8 及更高版本中更受欢迎。

【讨论】:

    猜你喜欢
    • 2014-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-02
    • 2021-02-09
    • 1970-01-01
    • 2019-12-29
    • 2020-09-12
    相关资源
    最近更新 更多