java泛型范围,Java泛型参数绑定到任何一个类型的范围

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 of a range of types (ie AND logic):

public class MyClass & Serializable> { } // legal syntax

Is there an OR logic version, ie something like this:

public class MyClass | Serializable> { } // illegal syntax

If there isn't a syntax that supports this (I don't think there is), is there a workaround or approach that is a good pattern?

For some context, one example use case might be:

/** @return true if the obj is either has the same id, or if obj is the same as id */

public boolean sameAs(T obj) {

if (obj instanceof String) return this.id.equals(obj);

if (obj instanceof MyClass) return this.id.equals(((MyClass)obj).id);

return false;

}

People seem to be getting hung up on the exact semantic of my method example above. Let's try this instead:

public class MyWrapper {

// my class can wrap A or B (unrelated classes). Yes I will probably use instanceof

}

EDITED:

I won't know at compile time which I might get (coming from external code), so I want to avoid having concrete classes for each type. Also, I have to give my class to a foreign system who invokes my class.method, but the other system can give me instances of a variety of classes, but a narrowly defined and known variety.

Some people have commented on instanceof being "impure". Well, one workaround is to use a factory method to pick my concrete class based on the class of the incoming object, but that factory method would have to use instanceof, so you're just moving the instanceof to another place - you still need the instanceof.

Or is this idea just not ever a good one?

解决方案

No. It wouldn't make any sense unless all the types had a non-empty union type, e.g. an interface they all implemented, or a base class they all extended, in which case you just specify the union type.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值