user11611653
user11611653

Reputation: 139

Can I use .getClass() == .class or .getClass() == .class.getClass()?

I'm testing if an Object is equals than a specific class type. For example:

@Override
public void itemStateChanged(ItemEvent e) {
    if (e.getStateChange() == ItemEvent.SELECTED) {
        Object sourceObject = e.getSource();

        if (sourceObject.getClass() == JComboBox.class.getClass()) {
            @SuppressWarnings("unchecked")
            JComboBox<String> jComboBox = (JComboBox<String>) sourceObject;

So, what comparison method should I use? sourceObject.getClass() == JComboBox.class.getClass() or sourceObject.getClass() == JComboBox.class?

Or simply use instanceof to compare if can I cast safety the e.getSource() to JComboBox?

Upvotes: 1

Views: 2451

Answers (3)

Andreas
Andreas

Reputation: 159135

If all you care about is whether the cast to JComboBox will work, then use:

if (sourceObject instanceof JComboBox) {

That way, any potential subclass of JComboBox will also be handled by your code, which is likely what should happen, since a subclass of JComboBox is a JComboBox.

Upvotes: 1

damientseng
damientseng

Reputation: 553

The short answer: sourceObject.getClass() == JComboBox.class is correct.

The result of someObj.getClass() is the Class object that represents the class of someObj.
And SomeClass.class is also the corresponding object that represents the class SomeClass.
So SomeClass.class.getClass() returns the Class object that represents the class of the object SomeClass.class

This code outputs true

Date d = new Date();
System.out.println(d.getClass() == Date.class);

While this gives a compilation error.

Date d = new Date();
System.out.println(d.getClass() == Date.class.getClass());

Upvotes: 2

Sarjit
Sarjit

Reputation: 809

case 1 :- if (sourceObject.getClass() == JComboBox.class) is correct way of comparsion as getClass() will return runtime class of sourceObject object and JComboBox.class will return class too

case 2:- sourceObject.getClass() == JComboBox.class.getClass() it will throw incompatible op-rend type Exception

Upvotes: 0

Related Questions