1

I have done a lot of searching around online and have come up with no information on this. My question is how does Java 8 internally handle Method Referencing e.g. Car::getWeight? Does it use Reflection, or is it an entirely new method of accessing a classes static and non-static methods?

I ask this because I have been learning about it recently and have become somewhat intrigued. I really enjoy the ability to handle function references just as though they were variables in languages like Python and JS. To be able to do this (in a somewhat limited capacity) in Java, is really exciting. Although, if the performance suffers much like with Reflection, it may not be such an exciting prospect.

Consider this example:

public class Main {

    private static List<String> shapes = new ArrayList<>();
    private static List<Supplier<Shape>> constrs = new ArrayList<>();

    static{
        constrs.add(Triangle::new);
        constrs.add(Square::new);
        shapes.add("triangle");
        shapes.add("square");
    }

    public static void main(String[] args){
        Shape x = constrs.get(shapes.indexOf("triangle")).get();

        Supplier<String> h = x::dothis;

        System.out.println(h.get());
    }
}

There is no way for the compiler to know of what type x is at compile time, so how can the compiler replace x::dothis with an anonymous method?

CraigR8806
  • 1,584
  • 13
  • 21
  • 2
    There's no need for reflection. The class and method name are available at compile time, after all. – user2357112 Jan 04 '17 at 18:25
  • What about the case where you may have a `List>` that holds different `Child::new` and programmatically a constructor is chosen? Will it still just replace each of those `Supplier`s with their respective constructors at compile time even if there is no logical path to them in the code? @user2357112 – CraigR8806 Jan 04 '17 at 18:30
  • 1
    It'll basically just write the same reflection-free anonymous classes you would have written if method references (and lambdas) weren't a thing. – user2357112 Jan 04 '17 at 18:33
  • @user2357112 I worked up an example to better illustrate my point, if you would like to take a look. I also did some mediocre grade (`System.nanoTime()`) testing on this and it seems that there is a significant performance lose when using method reference instead of direct method invocation. – CraigR8806 Jan 04 '17 at 19:54
  • Hmm. The implementation appears to be [way](http://docs.oracle.com/javase/8/docs/api/java/lang/invoke/LambdaMetafactory.html) more [complex](http://stackoverflow.com/questions/23983832/is-method-reference-caching-a-good-idea-in-java-8) than the user-level explanation and "equivalent to"s made it seem. – user2357112 Jan 04 '17 at 20:06

0 Answers0