Uploaded image for project: 'Groovy'
  1. Groovy
  2. GROOVY-8441

IllegalAccessError when calling a public method on a field whose type is declared to be a package-private implementation one

    XMLWordPrintableJSON

Details

    Description

      This seems somewhat similar to GROOVY-7549.

      Consider the following interface:

      package test18;
      
      public interface Iface {
      	String getBar();
      }
      

      and a package-private implementation:

      package test18;
      
      class IfaceImpl implements Iface {
      
      	@Override
      	public String getBar() {
      		return "bar";
      	}
      }
      

      Now the following base class:

      package test18;
      
      public class Base {
      
      	private IfaceImpl foo = new IfaceImpl(); 
      	
      	public Iface getFoo() {
      		return foo;
      	}
      }
      

      Please note: the field is declared with the implementation type, the getter is public, but the getter declared return type is the public interface.

      Then this Groovy class:

      package test18.sub
      
      import groovy.transform.CompileDynamic
      import groovy.transform.CompileStatic
      import test18.Base
      
      class Test18 extends Base {
      	
      	@CompileStatic
      	void foobar() {
      		println foo.bar
      	}
      	
      	static main(args) {
      		Test18 t = new Test18()
      		println t.foo.bar
      		t.foobar()
      	}
      }
      

      Please note the package is different.

      If you run this code, the first bar is written correctly, the second invocation fails with: java.lang.IllegalAccessError: tried to access class test18.IfaceImpl from class test18.sub.Test18.

      Workarounds:

      • remove @CompileStatic from Test18.foobar() (or declare it with @CompileDynamic if the whole class is statically compiled)
      • change the declaration of Base.foo to be of type Iface rather than IfaceImpl

      Attachments

        Activity

          People

            emilles Eric Milles
            mauromol Mauro Molinari
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: