Any reason to prefer getClass() over instanceof when generating .equals()?

I’m using Eclipse to generate .equals() and .hashCode(), and there is an option labeled “Use ‘instanceof’ to compare types”. The default is for this option to be unchecked and use .getClass() to compare types. Is there any reason I should prefer .getClass() over instanceof? Without using instanceof: if (obj == null) return false; if (getClass() … Read more

Why does instanceof return false for some literals?

“foo” instanceof String //=> false “foo” instanceof Object //=> false true instanceof Boolean //=> false true instanceof Object //=> false false instanceof Boolean //=> false false instanceof Object //=> false 12.21 instanceof Number //=> false /foo/ instanceof RegExp //=> true // the tests against Object really don’t make sense Array literals and Object literals match… … Read more

What is the difference between typeof and instanceof and when should one be used vs. the other?

In my particular case: callback instanceof Function or typeof callback == “function” does it even matter, what’s the difference? Additional Resource: JavaScript-Garden typeof vs instanceof 25 Answers 25 Use instanceof for custom types: var ClassFirst = function () {}; var ClassSecond = function () {}; var instance = new ClassFirst(); typeof instance; // object typeof … Read more

What is the difference between instanceof and Class.isAssignableFrom(…)?

Which of the following is better? a instanceof B or B.class.isAssignableFrom(a.getClass()) The only difference that I know of is, when ‘a’ is null, the first returns false, while the second throws an exception. Other than that, do they always give the same result? 14 s 14 When using instanceof, you need to know the class … Read more