问题
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?
回答1:
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
回答2:
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());
回答3:
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.
来源:https://stackoverflow.com/questions/59538976/can-i-use-getclass-class-or-getclass-class-getclass