简体   繁体   English

如何使用包私有构造函数创建类?

[英]How to create a class with a package private constructor?

I'm working on a library where I want to return an object representing a real world object. 我在一个图书馆里工作,我想返回一个代表真实世界对象的对象。 I want to expose this class to developers to manipulate the real world object, but I don't want to allow them to construct these objects themselves. 我想向开发人员展示此类,以操纵真实世界的对象,但我不想让他们自己构造这些对象。

Example

public class World {
    public static List<RealObject> getAllObjects() {
        // How to create RealObject with physicalID?
    }
}

public class RealObject {
    private int physicalID;

    public RealObject(int physicalID) {
        // Undesirable, user has no knowledge of IDs
    }

    public void setState(int state) {
        // Code using physicalID to change state
    }
}

These objects currently have no constructor and have a private id field that I set with reflection from within my library. 这些对象目前没有构造函数,并且具有一个私有id字段,该字段是我从库中反射设置的。 This works perfectly, but I can't help but think there must be a better solution. 这很完美,但是我不禁认为必须有一个更好的解决方案。 Perhaps a useful constraint in my situation is that it only needs to be possible to construct this object from one other class. 在我的情况下,也许有用的约束是只需要从另一个类构造此对象即可。

Is there a better solution? 有更好的解决方案吗? And is it still possible to have the class in a separate file in that case for organizational purposes? 在这种情况下,出于组织目的,是否仍可以将类放在单独的文件中?

If you put default access level on constructor (or any other method), then can be accessed only by classes from same package. 如果将默认访问级别放在构造函数(或任何其他方法)上,则只能由同一包中的类访问。

To concretely answer the question in the title: 要具体回答标题中的问题:

public class RealObject {
  RealObject(int physicalID) {
    // Package-private constructor
  }
}

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

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