简体   繁体   English

公开一个类的`final static Set`

[英]Expose `final static Set` of a class

I have a class that has:我有一堂课:
public static final Set<String> IDS = new HashSet<>(); , ,
whose values are initiated in a static block after running some query (Therefore I can't declare it as unmodifiableSet ).其值在运行某些查询后在静态块中启动(因此我不能将其声明为unmodifiableSet )。

Now that other classes need to use IDS but apparently I don't want to let them get direct access to it to avoid IDS being changed by callers.现在其他类需要使用IDS但显然我不想让他们直接访问它以避免调用者更改IDS
To achieve this, one way I can think of, is to为了实现这一点,我能想到的一种方法是

  1. make IDS privateIDS私有
  2. create a getter method that will return new HashSet<>(IDS) (or ImmutableSet as I'm using Guava )创建一个 getter 方法,该方法将return new HashSet<>(IDS) (或ImmutableSet ,因为我正在使用Guava

But wondering if there are better ways?但想知道是否有更好的方法?

You could use a temporary Set in your static block您可以在静态块中使用临时 Set

public static final Set<String> IDS;
static {
    final Set<String> temp = new HashSet<>();
    // Run your query and add ids to temp
    IDS = Collections.unmodifiableSet(temp);
}

Try this.尝试这个。

public static final Set<String> IDS;
static {
    Set<String> set = new HashSet<>();
    set.add("a");
    set.add("b");
    set.add("c");
    IDS = Collections.unmodifiableSet(set);
}


public static void main(String[] args) {
    System.out.println(IDS);
    IDS.add("x");
}

output:输出:

[a, b, c]
Exception in thread "main" java.lang.UnsupportedOperationException

If you want to expose a set (or any other collection) from your class, you could use java.util.Collections#unmodifiableSet .如果你想从你的类中公开一个集合(或任何其他集合),你可以使用java.util.Collections#unmodifiableSet It is very lightweight, because it just wraps your set and proxies all non-modifying calls to the underlying set.它非常轻量级,因为它只是包装您的集合并代理所有对基础集合的非修改调用。

And keep the state hidden.并保持状态隐藏。 One class should at most expose constants, better add a getter for the collection.一个类最多应该公开常量,最好为集合添加一个getter。

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

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