执行此操作的常用方法是根本不公开该类,而只是向该类公开接口。一个面向公众的接口和一个面向开发人员的接口。
然后,您需要一个工厂来创建它们。
/**
 * Expose this interface to the public.
 */
public interface INKMPMission {
    public String getName();
    public int getAge();
}
/**
 * Only expose this interface to developers.
 */
interface IDeveloperNKMPMission {
    public void setName(String name);
    public void setAge(int age);
}
public static class NKMPMissionFactory {
    /**
     * Expose only the INKMPMission construction.
     */
    public INKMPMission make(String name, int age) {
        return new NKMPMission(name, age);
    }
    /**
     * Protected version for developers.
     */
    IDeveloperNKMPMission forDeveloper(INKMPMission it) {
        return IDeveloperNKMPMission.class.cast(it);
    }
    /**
     * Private so no-one outside the factory knows about the inner workings.
     */
    private static class NKMPMission implements INKMPMission, IDeveloperNKMPMission {
        private String name;
        private int age;
        private NKMPMission(String name, int age) {
            this.name = name;
            this.age = age;
        }
        @Override
        public String getName() {
            return name;
        }
        @Override
        public int getAge() {
            return age;
        }
        @Override
        public void setName(String name) {
            this.name = name;
        }
        @Override
        public void setAge(int age) {
            this.age = age;
        }
    }
}
对于真正的偏执狂,您甚至可以使用代理。这将使通过反射使用设置器变得困难(但并非不可能)。
    /**
     * Expose only the INKMPMission construction.
     */
    public INKMPMission make(String name, int age) {
        return new NKMPMissionProxy(new NKMPMission(name, age));
    }
    /**
     * Protected version for developers.
     */
    protected IDeveloperNKMPMission forDeveloper(INKMPMission it) {
        if (it instanceof NKMPMissionProxy) {
            it = ((NKMPMissionProxy) it).theMission;
        }
        return IDeveloperNKMPMission.class.cast(it);
    }
    /**
     * A proxy for the truly paranoid - makes using reflection more difficult (but not impossible)
     */
    private static class NKMPMissionProxy implements INKMPMission {
        private final NKMPMission theMission;
        private NKMPMissionProxy(NKMPMission theMission) {
            this.theMission = theMission;
        }
        @Override
        public String getName() {
            return theMission.getName();
        }
        @Override
        public int getAge() {
            return theMission.getAge();
        }
    }