1

I've noticed the strange behavior with package scope in Java and Android.

  1. I've created the package "java.util.concurrent" in my project
  2. Next I added class TestClass in just created package

    package java.util.concurrent;
    
    public class TestClass {
    
       public void testMethod() {
    
           ArrayBlockingQueue s = new ArrayBlockingQueue(1);
           // I can use items field.
           Object[] items = s.items;
    
       }
    
    }
    
  3. The field items of ArrayBlockingQueue class has final package scope

    public class ArrayBlockingQueue<E> extends AbstractQueue<E>
            implements BlockingQueue<E>, java.io.Serializable {
    
    
        ....                
    
        /** The queued items */
        final Object[] items;
    
        ....
    
    }
    

Next, when I'm trying to compile the TestClass with usual Java Project (java 1.8.6x). I get success and it's logical.

But same class in Android project returns compile time error. The reason is 'my class hasn't access to this field'.

Have you any ideas?

UPDATE

The screen bellow displays the version of Android and code of Queue class

enter image description here

kemenov
  • 409
  • 4
  • 13

1 Answers1

1

It would seem that the Android version of ArrayBlockingQueue is not the same as the Java version. In Android, the items are actually private. That would make sense as to why it is out of scope. You can work around this, with reflection you can gain access to private variables (not sure about final private)

Community
  • 1
  • 1
Kevin
  • 1,626
  • 16
  • 30
  • Kevin's right. For example: openjdk defines items as: `private final E[] items;` – Shloim Nov 26 '15 at 13:32
  • Wow, can't believe I made that mistake (that its openjdk instead of android source). Thanks for the correct – Kevin Nov 26 '15 at 13:34
  • I've added screen which displays the version of Android and items field with package scope. – kemenov Nov 26 '15 at 13:50
  • 1
    I can't find a good explanation for you on this. I agree, it should be working. Might be some android witchcraft at work resulting in your class not actually being in the same package. – Kevin Nov 26 '15 at 14:07
  • @Kevin Yep, I agree with you, I found other classes with same behavior in Android and it's very strange. – kemenov Nov 26 '15 at 14:24