Forum Stats

  • 3,769,586 Users
  • 2,252,984 Discussions
  • 7,875,105 Comments

Discussions

Lambda Expression throws IllegalAccessError

csh
csh Member Posts: 525
edited Jan 28, 2015 8:18AM in Java 8 Questions

Hi,

I have the following structure and want to use lambda expressions with it, but an exception occurs:

class SuperClass // (package private)

public class SubClass extends SuperClass // in same package as SuperClass

I have a functional interface (a listener), which has one argument of type SubClass.

public interface MyListener() {
    void myMethod(SubClass e);
}

When I use the old-school Java 7 style:

addListener(new MyListener() {
     @Override
     public void myMethod(SubClass e) {
         System.out.println(e);
     }
});

everything works fine!

If I use Java 8 lambda expression instead:

addListener(e -> {
    System.out.println(e);
});

it will throw an exception:

java.lang.IllegalAccessError: tried to access class SuperClass

I wonder if this is a documented shortcoming of Java 8 lambda expressions or a bug?

Can somebody help here?

Answers

  • dvohra21
    dvohra21 Member Posts: 14,250 Gold Crown

    Is the SuperClass in the default package? Classes from the default package do not get imported. The error should also be in Java 7 if the same package structure is used.

  • csh
    csh Member Posts: 525

    No, it's in a "real" package, like "com.example". Java 7 does not support Lambdas.

  • James_D
    James_D Member Posts: 1,496 Gold Trophy

    I tried this, or something similar (under 1.8.0u40 ea) and it worked fine.

    My code:

    SuperClass.java:

    package pri;
    
    class SuperClass { }
    

    SubClass.java:

    package pri;
    
    public class SubClass extends SuperClass { }
    

    MyLIstener.java (different package):

    package pub;
    
    import pri.SubClass;
    
    @FunctionalInterface
    public interface MyListener {
      void myMethod(SubClass e) ;
    }
    

    Test.java (another package still):

    package test;
    
    
    import pri.SubClass;
    import pub.MyListener;
    
    
    public class Test {
    
    
      public static void main(String[] args) {
          MyListener l = new MyListener() {
              @Override
              public void myMethod(SubClass e) {
                  System.out.println(e);    
              }
          };
    
          MyListener l2 = e -> System.out.println(e);
    
          MyListener l3 = System.out::println ;
    
          l.myMethod(new SubClass());
          l2.myMethod(new SubClass());
          l3.myMethod(new SubClass());
      }
    
    
    }
    
  • csh
    csh Member Posts: 525

    Sorry, it turned out, that the problem only exists, when there are generics involved (i.e. class SuperClass<T>). I've got an example at home, if you are interested.

    In the meanwhile I met an Oracle guy (at Devoxx), who said, it looks like a bug in Java 8. I don't know where it's tracked.