Does Java 8's Method Reference use Reflection?

115 views Asked by At

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?

0

There are 0 answers