简体   繁体   English

Java和Android中的包作用域访问

[英]package scope access in Java and Android

I've noticed the strange behavior with package scope in Java and Android. 我注意到Java和Android中包作用域的奇怪行为。

  1. I've created the package "java.util.concurrent" in my project 我在项目中创建了包“ java.util.concurrent”
  2. Next I added class TestClass in just created package 接下来,我在刚创建的包中添加了TestClass类

     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 ArrayBlockingQueue类的字段项具有最终的包范围

     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). 接下来,当我尝试使用常规Java项目(java 1.8.6x)编译TestClass时。 I get success and it's logical. 我获得成功,这是合乎逻辑的。

But same class in Android project returns compile time error. 但是Android项目中的同一个类会返回编译时错误。 The reason is 'my class hasn't access to this field'. 原因是“我的班级无法访问此字段”。

Have you any ideas? 你有什么想法吗?

UPDATE UPDATE

The screen bellow displays the version of Android and code of Queue class 屏幕下方显示了Android版本和Queue类的代码

在此处输入图片说明

It would seem that the Android version of ArrayBlockingQueue is not the same as the Java version. 似乎ArrayBlockingQueue的Android版本与Java版本不同。 In Android, the items are actually private . 在Android中, items 实际上是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) 您可以解决此问题,通过反射可以访问私有变量 (不确定最终私有变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM