如何确定两个参数是否是同一但未知类的实例?
假设我们有一个方法,它接受两个 Object 类型的参数 o1 和 o2 并返回一个布尔值。我希望此方法仅当参数是同一类的实例时才返回 true,例如:
foo(new Integer(4),new Integer(5));
应该返回 true,但是:
foo(new SomeClass(), new SubtypeSomeClass());
应该返回 false 以及:
foo(new Integer(3),"zoo");
应该返回 false。
我相信一种方法是比较完全限定的类名:
public boolean foo(Object o1, Object o2){
Class<? extends Object> c1 = o1.getClass();
Class<? extends Object> c2 = o2.getClass();
if(c1.getName().equals(c2.getName()){ return true;}
return false;
}
另一种条件语句是:
if (c1.isAssignableFrom(c2) && c2.isAssignableFrom(c1)){ return true; }
后一种选择相当慢。这个问题还有其他替代方案吗?
Let us say we have a method which accepts two arguments o1 and o2 of type Object and returns a boolean value. I want this method to return true only when the arguments are instances of the same class, e.g.:
foo(new Integer(4),new Integer(5));
Should return true, however:
foo(new SomeClass(), new SubtypeSomeClass());
should return false and also:
foo(new Integer(3),"zoo");
should return false.
I believe one way is to compare the fully qualified class names:
public boolean foo(Object o1, Object o2){
Class<? extends Object> c1 = o1.getClass();
Class<? extends Object> c2 = o2.getClass();
if(c1.getName().equals(c2.getName()){ return true;}
return false;
}
An alternative conditional statement would be :
if (c1.isAssignableFrom(c2) && c2.isAssignableFrom(c1)){ return true; }
The latter alternative is rather slow. Are there other alternatives to this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不要理会完全限定的类名 - 只需比较类引用:
类在名称和类加载器方面本质上是唯一的 - 因此如果对象属于同一类名称但由不同的类加载,则这将返回 false类加载器,但这可能是合适的:除了名称之外,它们可能是完全不同的类!但是,如果类具有相同的名称和类加载器,它们将具有相同的引用。
请注意,如果
o1
或o2
为 null,这将抛出NullPointerException
,但这可能正是您想要的。Don't bother with the fully qualified class names - just compare class references:
Classes are essentially unique by name and classloader - so this will return false if the objects are of the same class name but loaded by different classloaders, but that's probably appropriate: they could be completely different classes in all but name! If the classes have the same name and classloader, however, they'll have the same reference.
Note that this will throw a
NullPointerException
if eithero1
oro2
is null, but again that's probably what you want.你的资格可以相当慢吗?与什么相比?另外请详细说明一下您的使用场景?在 java 中,Object api 包含 equals/hashCode 方法配对,用于识别对象之间的相等性。看起来这就是您可能试图找到的内容,即:
在这种情况下,在 SomeClass 中重写 equals 的最佳实现如下:
确保您在对象中提供标识。
Can you qualify rather slow? Compared to what? Also please elaborate your usage scenario? In java the Object api includes a equals/hashCode method paring that should be used to identify equality between objects. It appears as if this is what you may be attempting to find, ie:
In this case, the best implementation for overriding equals in SomeClass is as follows:
Making sure you provide an identity within your object.