[英]Is there a way to use package-private in java to allow other packages access?
So I've been working in C# for a number of years and am now working in Java. 因此,我从事C#已有多年,现在正在使用Java。 In C#, you can use the internal keyword to hide a class/method from public view but allow certain assemblies/packages access if you specifically grant it.
在C#中,您可以使用internal关键字在公共视图中隐藏类/方法,但如果您特别授予许可,则允许某些程序集/程序包访问。 As I look around in Java I don't see anything that is directly the same as internal.
当我在Java中四处查看时,看不到与内部直接相同的任何东西。
I found out about package-private. 我发现了关于包私有的。 However, this keeps it completely hidden from the outside world.
但是,这使它完全对外界隐藏。 Is there a way in Java to allow certain other packages access to internal code without making it public?
Java中是否有一种方法可以允许某些其他程序包在不公开的情况下访问内部代码?
If you are asking why I would do this answers are generally unit / integration testing or a need to have certain, trusted packages access to code as to not duplicate it. 如果您问我为什么要这样做,那么答案通常是单元/集成测试,或者需要让某些受信任的程序包访问代码以免重复。 I know some people think you shouldn't test private / internal code.
我知道有人认为您不应该测试私有/内部代码。 I also know that allowing inside access is not generally good software engineering.
我也知道,允许内部访问通常不是好的软件工程。 I'm not really interested in discussion on these topics, just curious if you can do what I want to do.
我对这些主题的讨论并不十分感兴趣,只是好奇您是否可以做我想做的事情。
Thanks. 谢谢。
Java does not have the concept of assemblies like in .NET (at least not yet). Java没有.NET中的程序集概念(至少现在还没有)。 The closest thing is OSGi bundles, which has this concept (x-internal, x-friend, etc), but that is not really core Java.
最接近的是OSGi捆绑软件,它具有这个概念(x-内部,x-朋友等),但这并不是Java的真正核心。
If you are not using OSGi, there should be no need go through this complication. 如果您不使用OSGi,则无需进行此复杂操作。 Just make sure your unit tests are in the same package as the class under test.
只要确保您的单元测试与被测类在同一个程序包中即可。 The Maven directory structure (which is a good choice even if you are not using Maven) sets you up for this with
src/main/java
, src/test/java
etc. Maven目录结构(即使您不使用Maven也是一个不错的选择),可以使用
src/main/java
, src/test/java
等设置它。
You can place your test into the same package name at another place. 您可以将测试放在另一个地方的相同程序包名称中。 This is treated as the same package and you can access the package private classes.
这被视为相同的程序包,您可以访问程序包私有类。 The test classes can be placed in another JAR file like
testSomething.jar
while the tested package is part on something.jar
. 可以将测试类放置在另一个JAR文件中,例如
testSomething.jar
而被测试的程序包则放在something.jar
。
This does not work with sealed packages. 这不适用于密封包装。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.