Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Lambda Expression throws IllegalAccessError

cshOct 16 2014 — edited Jan 28 2015

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?

Comments

dvohra21

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

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

James_D

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

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.

1 - 4

Post Details

Added on Oct 16 2014
4 comments
1,967 views