java 泛型 比较,Java泛型:比较Object的类到< E>

Let's say I have the following class:

public class Test {

public boolean sameClassAs(Object o) {

// TODO help!

}

}

How would I check that o is the same class as E?

Test test = new Test();

test.sameClassAs("a string"); // returns true;

test.sameClassAs(4); // returns false;

I can't change the method signature from (Object o) as I'm overridding a superclass and so don't get to choose my method signature.

I would also rather not go down the road of attempting a cast and then catching the resulting exception if it fails.

解决方案

An instance of Test has no information as to what E is at runtime. So, you need to pass a Class to the constructor of Test.

public class Test {

private final Class clazz;

public Test(Class clazz) {

if (clazz == null) {

throw new NullPointerException();

}

this.clazz = clazz;

}

// To make things easier on clients:

public static Test create(Class clazz) {

return new Test(clazz);

}

public boolean sameClassAs(Object o) {

return o != null && o.getClass() == clazz;

}

}

If you want an "instanceof" relationship, use Class.isAssignableFrom instead of the Class comparison. Note, E will need to be a non-generic type, for the same reason Test needs the Class object.

For examples in the Java API, see java.util.Collections.checkedSet and similar.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值