标签: method-reference

具有不同arities的重载方法的方法引用无效

尝试编译表达式时Comparator.comparing(String::toLowerCase),Java编译器返回错误.有关更多信息,请参阅以下问题:

为什么Comparator.comparing不能与String :: toLowerCase方法引用一起使用?


我试图尽可能地减少这个问题.特别是,我已经删除了几乎所有依赖项到其他类.的主要方法包括两个方法调用.第一个语句编译时没有错误,而第二个语句产生错误.

interface Fun<T, R> { R apply(T t); }

public final class Foo {
    public static void main(String... args) {
        invoke(Foo::bar); // OK
        invoke(Foo::baz); // ERROR
    }
    private static <T, U> void invoke(Fun<T, U> f) { }
    private String bar() { return null; }
    private String baz() { return null; }
    private String baz(Integer i, Integer j) { return null; }
}
Run Code Online (Sandbox Code Playgroud)

这很奇怪,因为第二个baz方法不适用于此上下文,因为参数数量不匹配.我看了JLS8(15.13).但是,它没有帮助,因为方法引用的规则非常复杂.

问:为什么第二种情况会出现编译错误?根据JLS真的会出现编译错误吗?根据对另一个问题的一些评论,Netbeans中没有编译错误.


作为参考,我使用的是JDK8版本1.8.0-b132.如果在命令行上编译程序,编译器将显示以下错误消息:

$ /opt/jdk8/bin/javac Foo.java
Foo.java:6: …
Run Code Online (Sandbox Code Playgroud)

java type-inference java-8 method-reference

7
推荐指数
1
解决办法
2534
查看次数

Java 8中静态方法引用的限制

我正在尝试使用方法引用来捕获方法调用,并且遇到了一些限制.这很好用:

<T> void capture(Function<T, ?> in) {
}

private interface Foo {
  String getBar();
} 

capture(Foo::getBar);
Run Code Online (Sandbox Code Playgroud)

但是,如果我将Foo.setBar的签名更改为以下内容:

private interface Foo {
  void setBar(String bar);
}

capture(Foo::setBar);
Run Code Online (Sandbox Code Playgroud)

我收到一个错误:

Cannot make a static reference to the non-static method setBar(String) from the type MyTest.Foo

我不清楚限制是什么.理想情况下,我想使用方法引用来捕获标准setter上的调用.有没有办法做到这一点?

java java-8 method-reference

7
推荐指数
2
解决办法
3153
查看次数

Java 8构造函数方法引用

我正在阅读perform message它附带的样本我重现..

@FunctionalInterface
public interface Action {
    public void perform();
}
Run Code Online (Sandbox Code Playgroud)

实施者

public final class ActionImpl implements Action {
    public ActionImpl() {
        System.out.println("constructor[ActionIMPL]");
    }

    @Override
    public void perform() {
        System.out.println("perform method is called..");
    }    
}
Run Code Online (Sandbox Code Playgroud)

来电者.

public final class MethodReferences {

    private final Action action;

    public MethodReferences(Action action) {
        this.action = action;
    }

    public void execute() {
        System.out.println("execute->called");
        action.perform();
        System.out.println("execute->exist");
    }

    public static void main(String[] args) {
        MethodReferences clazz = new MethodReferences(new ActionImpl());
        clazz.execute();
    }
}
Run Code Online (Sandbox Code Playgroud)

如果调用此方法则将以下内容打印到输出中

constructor[ActionIMPL] …
Run Code Online (Sandbox Code Playgroud)

java java-8 method-reference constructor-reference

7
推荐指数
1
解决办法
5372
查看次数

带数组构造函数的引用方法

我尝试ArrayType[]::new在以下示例中使用带有表达式的引用方法:

public class Main
{
    public static void main(String[] args)
    {
        test1(3,A[]::new);
        test2(x -> new A[] { new A(), new A(), new A() });

        test3(A::new);
    }

    static void test1(int size, IntFunction<A[]> s)
    {
        System.out.println(Arrays.toString(s.apply(size)));
    }

    static void test2(IntFunction<A[]> s)
    {
        System.out.println(Arrays.toString(s.apply(3)));
    }

    static void test3(Supplier<A> s)
    {
        System.out.println(s.get());
    }
}

class A
{
    static int count = 0;
    int value = 0;

    A()
    {
        value = count++;
    }

    public String toString()
    {
        return Integer.toString(value);
    }
}
Run Code Online (Sandbox Code Playgroud)

产量

[null, …
Run Code Online (Sandbox Code Playgroud)

java java-8 method-reference

7
推荐指数
1
解决办法
500
查看次数

"String [] :: new"是什么意思?

我正在学习如何使用流,我遇到了这个方法的问题.

public static String[] inArray(String[] array1, String[] array2) {
   return Arrays.stream(array1)
  .filter(str -> Arrays.stream(array2).anyMatch(s -> s.contains(str)))
  .distinct().sorted().toArray(**String[]::new**);
}
Run Code Online (Sandbox Code Playgroud)

我很困惑String[]::new,你能给我一个暗示吗?

java java-8 java-stream method-reference

7
推荐指数
5
解决办法
3124
查看次数

lambda表达式与实例化方法引用之间的不同行为

据我所知,lambda表达式可以被方法引用替换而没有任何问题.我的IDE说的相同,但下面的例子显示了相反的情况.方法引用清楚地返回相同的对象,其中lambda表达式每次都返回新对象.

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Instance {

    int member;

    Instance set(int value){
        this.member = value;
        return this;
    }

    @Override
    public String toString() {
        return member + "";
    }

    public static void main(String[] args) {

        Stream<Integer> stream1 = Stream.of(1, 2, 3, 4);
        Stream<Integer> stream2 = Stream.of(1, 2, 3, 4);

        List<Instance> collect1 = stream1.map(i -> new Instance().set(i)).collect(Collectors.toList());
        List<Instance> collect2 = stream2.map(new Instance()::set).collect(Collectors.toList());

        System.out.println(collect1);
        System.out.println(collect2);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的输出:

[1, 2, 3, 4]
[4, 4, 4, 4]
Run Code Online (Sandbox Code Playgroud)

java lambda java-stream method-reference

7
推荐指数
2
解决办法
142
查看次数

Optional.map中的Integer :: toString

在Java中使用带方法引用的map时,我遇到了以下问题:

public class Dummy {

  public static void main(String[] args) {
    IntegerHolder ih = new IntegerHolder();
    Optional<IntegerHolder> iho = Optional.of(ih);
    iho.map(IntegerHolder::getInteger).map(Objects::toString);
    iho.map(IntegerHolder::getInteger).map((Integer ii) ->ii.toString());
    iho.map(IntegerHolder::getInteger).map(Integer::toString);// this line will not compile. The error is "non-static method toString() cannot be referenced from a static context" 
  }

  private static class IntegerHolder {
    private Integer i;
    Integer getInteger() {return i;}
 }
}
Run Code Online (Sandbox Code Playgroud)

在我看来,Integer :: toString与IntegerHolder :: getInteger相同.两者都是"引用特定类型的任意对象的实例方法"我不明白为什么一个工作,但另一个不工作.你能否对这个问题有所了解?非常感谢你.

java method-reference

7
推荐指数
1
解决办法
316
查看次数

调用带有空参数的任意对象的方法引用时发生NullPointerException

我试图创建对任意对象的方法引用,因此定义了以下类型:

interface I {
    boolean get(Impl impl);
}

static class Impl {
    public boolean get() {
        return true;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,我声明了方法引用,如下所示:

I i = Impl::get;
Run Code Online (Sandbox Code Playgroud)

当我打电话时:

i.get(null);
Run Code Online (Sandbox Code Playgroud)

我得到了NullPointerException:

Exception in thread "main" java.lang.NullPointerException
Run Code Online (Sandbox Code Playgroud)

有人可以解释为什么即使没有在Impl任何地方使用参考文件也会发生这种情况吗?

java method-reference

7
推荐指数
1
解决办法
51
查看次数

如何通过反射获取方法引用?

假设我有一些像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)

java reflection java-8 method-reference

6
推荐指数
0
解决办法
93
查看次数

为什么必须为方法引用显式指定类/对象名?

当我想引用当前作用域中的方法时,我仍然需要指定类名(对于静态方法)或者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中没有实现这样或类似的语法?这种语法会出现什么问题吗?或者根本不考虑它?

java java-8 method-reference

6
推荐指数
1
解决办法
271
查看次数