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

喜欢而已 提交于 2020-01-05 04:10:50

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!