Java generics parameter bounding to any of a range of types

后端 未结 5 1530
一向
一向 2020-12-10 12:26

Is there a syntax or workaround to constrain a generic type parameter to any of a range of types?

I am aware that you can constrain a type to be all

5条回答
  •  天涯浪人
    2020-12-10 13:14

    The following code would do the same thing as in the provided example, but without runtime type checking and typecasts.

    public boolean sameAs(MyClass obj) {
        return this.id.equals(obj.id);
    }
    public boolean sameAs(String obj) {
        return this.id.equals(obj);
    }
    

    NPE checking might be a good idea.

提交回复
热议问题