Java使用泛型来获取所有实例的列表

时间:2017-08-16 19:45:00

标签: java

我有一个带有一些静态成员的静态类:

public static class Foo {
private static Bar one = new Bar();
private static Bar two = new Bar();
private static Bar three = new Bar();
...
private static Bar n = new Bar();
}

我希望有一个返回所有Bar的方法:

public static List<Bar> getBars()

您能告诉我如何使用Java泛型获取所有实例吗?

2 个答案:

答案 0 :(得分:0)

您是否在考虑类似安全枚举模式的修改版本?

import java.util.ArrayList;
import java.util.List;

public class TypeSafeEnum{
    private String data=null;
    private static List<TypeSafeEnum> list=new ArrayList<>();
    private TypeSafeEnum(String data){
        this.data=data;
        list.add(this);
    }
    private static TypeSafeEnum One=new TypeSafeEnum("one");
    private static TypeSafeEnum Two=new TypeSafeEnum("two");
    private static TypeSafeEnum Three=new TypeSafeEnum("three");
    private static TypeSafeEnum Four=new TypeSafeEnum("four");
    public String getValue(){
        return data;
    }
    public static List<TypeSafeEnum> getMembers(){
        return list;
    }
}

用这个你可以做类似

的事情
public class Test{
    public static void main(String[]args){
        for(TypeSafeEnum member:TypeSafeEnum.getMembers()){
            System.out.println(member.getValue());
        }
    }
}

并获取

one
two
three
four

答案 1 :(得分:-1)

试试这样:

public static List<Bar> getBars(){
    List<Bar> res = new ArrayList<Bar>();
    res.add(one);
    res.add(two);
    ...
    res.add(n);
    return res;
}