如何在Java中实现通用方法来管理类的属性?

如何在Java中实现通用方法来管理类的属性?,java,oop,Java,Oop,我有一个包含两个集合的容器类:一个是a类型,另一个是B类型。我想在我的类中有一个方法,它可以接收a或B类型的参数,并将其添加到相应的集合中。 顺便说一句,我不确定是否应该使用接口Something。请注意,我希望避免使用getClass()或instanceof检查收到的参数的类类型,因为我的项目中有很多集合 我怎样才能做到这一点 谢谢 public class Container{ privte Set<A> a; privte Set<B> b; public C

我有一个包含两个集合的容器类:一个是
a
类型,另一个是
B
类型。我想在我的类中有一个方法,它可以接收
a
B
类型的参数,并将其添加到相应的集合中。 顺便说一句,我不确定是否应该使用接口
Something
。请注意,我希望避免使用
getClass()
instanceof
检查收到的参数的类类型,因为我的项目中有很多集合

我怎样才能做到这一点

谢谢

public class Container{

privte Set<A> a;
privte Set<B> b;

public Container(){
    a = new HashSet<>();
    b = new HashSet<>();
}

//getters and setters

//generic method
public void addAorB(Something instance){
    //add to the coresponding Set
}
}

public class A implements Something{

}

public class B implements Something{

}
公共类容器{
private集a;
private集b;
公共容器(){
a=新的HashSet();
b=新的HashSet();
}
//接球手和接球手
//通用方法
public void addAorB(某物实例){
//添加到共同响应集
}
}
公共类A实现了一些东西{
}
公共类B实现了一些东西{
}

假设泛型类型是不相交的,我会将所有集合放入一个映射中,每个集合的类型都作为键。为了避免重复代码,我还将创建一个方法来创建集合并将其放入映射中

private final Map<Class<?>, Set<? extends Something>> sets = new HashMap<>();

public Container() {
    a = createAndPut(A.class);
    b = createAndPut(B.class);
}

private <T extends Something> Set<T> createAndPut(Class<T> type) {
    Set<T> set = new HashSet<>();
    sets.put(type, set);
    return set;
}

private final Map正打算提出类似的建议!抱歉,我没有注意到您希望避免使用instanceof
private final Map<Class<?>, Set<? extends Something>> sets = new HashMap<>();

public Container() {
    a = createAndPut(A.class);
    b = createAndPut(B.class);
}

private <T extends Something> Set<T> createAndPut(Class<T> type) {
    Set<T> set = new HashSet<>();
    sets.put(type, set);
    return set;
}
public void addAorB(Something instance){
        Set<? extends Something> set = sets.get(instance.getClass());
        if (set == null)
            set = createAndPut(instance.getClass());
        ((Set<Something>) set).add(instance);
}