instanceof 与 getClass( )

发布于 2024-10-17 09:47:18 字数 890 浏览 6 评论 0原文

我发现使用 getClass()== 运算符优于 instanceOf 运算符时性能有所提高。

Object str = new Integer("2000");

long starttime = System.nanoTime();

if (str instanceof String) {
    System.out.println("its string");
} else {
    if (str instanceof Integer) {
        System.out.println("its integer");
        
    }
}

System.out.println((System.nanoTime() - starttime));

starttime = System.nanoTime();

if (str.getClass() == String.class) {
    System.out.println("its string in equals");
} else {
    if (str.getClass() == Integer.class) {
        System.out.println("its integer");
    }
}

System.out.println((System.nanoTime() - starttime));

是否有任何指南,使用 getClass()instanceOf 哪一个?

给定一个场景:我知道要匹配的确切类,即 StringInteger (这些是最终类)等。

正在使用 instanceOf操作员的不良做法?

I see gain in performance when using getClass() and == operator over instanceOf operator.

Object str = new Integer("2000");

long starttime = System.nanoTime();

if (str instanceof String) {
    System.out.println("its string");
} else {
    if (str instanceof Integer) {
        System.out.println("its integer");
        
    }
}

System.out.println((System.nanoTime() - starttime));

starttime = System.nanoTime();

if (str.getClass() == String.class) {
    System.out.println("its string in equals");
} else {
    if (str.getClass() == Integer.class) {
        System.out.println("its integer");
    }
}

System.out.println((System.nanoTime() - starttime));

Is there any guideline, which one to use getClass() or instanceOf?

Given a scenario: I know exact classes to be matched, that is String, Integer (these are final classes), etc.

Is using instanceOf operator bad practice ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

一笔一画续写前缘 2024-10-24 09:47:18

instanceofgetClass() == ... 的性能1之所以不同,是因为它们在做不同的事情。

  • instanceof 测试左侧 (LHS) 的对象引用是否是右侧 (RHS) 类型的实例或某个子类型 .

  • getClass() == ... 测试类型是否相同。

因此,建议忽略性能问题并使用能为您提供所需答案的替代方案。

使用 instanceOf 运算符是不好的做法2吗?

未必。过度使用 instanceOfgetClass() 可能“设计味道”。如果您不小心,您最终会得到这样的设计:添加新子类会导致大量代码返工。在大多数情况下,首选方法是使用多态性。

然而,在某些情况下,这些并不是“设计气味”。例如,在 equals(Object) 中,您需要测试参数的实际类型,如果不匹配则返回 false。最好使用 getClass() 来完成此操作。


1 - 我的答案是假设假设有良好的性能结果表明getClass()更快。您提出的基准在许多方面都有缺陷,我们不能相信它产生的结果;请参阅如何用 Java 编写正确的微基准测试?。不管怎样,我提出的观点与表现无关!
2 - 应谨慎使用“最佳实践”、“不良实践”、“设计味道”、“反模式”等术语,并以怀疑的态度对待。他们鼓励非黑即白的思维。最好根据具体情况做出判断,而不是纯粹基于教条;例如,有人说是“最佳实践”。我建议每个人都阅读无最佳实践(如果他们还没有这样做的话)。< /sup>

The reason that the performance1 of instanceof and getClass() == ... is different is that they are doing different things.

  • instanceof tests whether the object reference on the left-hand side (LHS) is an instance of the type on the right-hand side (RHS) or some subtype.

  • getClass() == ... tests whether the types are identical.

So the recommendation is to ignore the performance issue and use the alternative that gives you the answer that you need.

Is using the instanceOf operator bad practice2 ?

Not necessarily. Overuse of either instanceOf or getClass() may be "design smell". If you are not careful, you end up with a design where the addition of new subclasses results in a significant amount of code reworking. In most situations, the preferred approach is to use polymorphism.

However, there are cases where these are NOT "design smell". For example, in equals(Object) you need to test the actual type of the argument, and return false if it doesn't match. This is best done using getClass().


1 - My answer was written assuming that there are sound performance results that show that getClass() is faster. The benchmark you presented is flawed in a number of respects, and we cannot trust the results it produces; see How do I write a correct micro-benchmark in Java?. Either way, the points I am making are independent of the performance!
2 - Terms like "best practice", "bad practice", "design smell", "antipattern" and so on should be used sparingly and treated with suspicion. They encourage black-or-white thinking. It is better to make your judgements in context, rather than based purely on dogma; e.g. something that someone said is "best practice". I recommend that everyone read No Best Practices if they haven't already done so.

浊酒尽余欢 2024-10-24 09:47:18

您是否想要完全匹配一个类,例如仅匹配FileInputStream而不是FileInputStream的任何子类?如果是这样,请使用 getClass()==。我通常会在 equals 中执行此操作,以便 X 的实例不被视为等于 X 的子类的实例 - 否则您可能会遇到棘手的对称问题。另一方面,这对于比较属于同一类的两个对象比比较一个特定类的对象更有用。

否则,请使用instanceof。请注意,使用 getClass() 时,您需要确保开始时有一个非空引用,否则您将得到一个 NullPointerException,而 instanceof<如果第一个操作数为 null,/code> 将仅返回 false

就我个人而言,我认为 instanceof 更惯用 - 但在大多数情况下,广泛使用它们中的任何一个都是一种设计味道。

Do you want to match a class exactly, e.g. only matching FileInputStream instead of any subclass of FileInputStream? If so, use getClass() and ==. I would typically do this in an equals, so that an instance of X isn't deemed equal to an instance of a subclass of X - otherwise you can get into tricky symmetry problems. On the other hand, that's more usually useful for comparing that two objects are of the same class than of one specific class.

Otherwise, use instanceof. Note that with getClass() you will need to ensure you have a non-null reference to start with, or you'll get a NullPointerException, whereas instanceof will just return false if the first operand is null.

Personally I'd say instanceof is more idiomatic - but using either of them extensively is a design smell in most cases.

感受沵的脚步 2024-10-24 09:47:18

我知道自从问这个问题以来已经有一段时间了,但我昨天学到了一个替代方案

我们都知道你可以这样做:

if(o instanceof String) {   // etc

但是如果你不确切知道它需要什么类型的课程怎么办?
通常你不能这样做:

if(o instanceof <Class variable>.getClass()) {   

因为它会给出编译错误。
相反,这里有一个替代方案 - isAssignableFrom()

例如:

public static boolean isASubClass(Class classTypeWeWant, Object objectWeHave) {

    return classTypeWeWant.isAssignableFrom(objectWeHave.getClass())
}

I know it has been a while since this was asked, but I learned an alternative yesterday

We all know you can do:

if(o instanceof String) {   // etc

but what if you dont know exactly what type of class it needs to be?
you cannot generically do:

if(o instanceof <Class variable>.getClass()) {   

as it gives a compile error.
Instead, here is an alternative - isAssignableFrom()

For example:

public static boolean isASubClass(Class classTypeWeWant, Object objectWeHave) {

    return classTypeWeWant.isAssignableFrom(objectWeHave.getClass())
}
笑忘罢 2024-10-24 09:47:18

getClass() 的限制是对象只能与同一类、同一运行时类型的其他对象相等,如以下代码的输出所示:

class ParentClass{
}
public class SubClass extends ParentClass{
    public static void main(String []args){
        ParentClass parentClassInstance = new ParentClass();
        SubClass subClassInstance = new SubClass();
        if(subClassInstance instanceof ParentClass){
            System.out.println("SubClass extends ParentClass. subClassInstance is instanceof ParentClass");
        }
        if(subClassInstance.getClass() != parentClassInstance.getClass()){
            System.out.println("Different getClass() return results with subClassInstance and parentClassInstance ");
        }
    }
}

输出:

子类扩展了父类。 subClassInstance是ParentClass的实例。

getClass()返回的结果与subClassInstance和parentClassInstance不同。

getClass() has the restriction that objects are only equal to other objects of the same class, the same run time type, as illustrated in the output of below code:

class ParentClass{
}
public class SubClass extends ParentClass{
    public static void main(String []args){
        ParentClass parentClassInstance = new ParentClass();
        SubClass subClassInstance = new SubClass();
        if(subClassInstance instanceof ParentClass){
            System.out.println("SubClass extends ParentClass. subClassInstance is instanceof ParentClass");
        }
        if(subClassInstance.getClass() != parentClassInstance.getClass()){
            System.out.println("Different getClass() return results with subClassInstance and parentClassInstance ");
        }
    }
}

Outputs:

SubClass extends ParentClass. subClassInstance is instanceof ParentClass.

Different getClass() return results with subClassInstance and parentClassInstance.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文