问题描述
我正在测试对象
是否等于特定的类
类型。
例如:
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;
那么,我应该使用哪种比较方法? sourceObject.getClass()== JComboBox.class.getClass()
或 sourceObject.getClass()== JComboBox.class
?
So, what comparison method should I use? sourceObject.getClass() == JComboBox.class.getClass()
or sourceObject.getClass() == JComboBox.class
?
还是简单地使用 instanceof
进行比较,是否可以将e.getSource()安全地投射到JComboBox?
Or simply use instanceof
to compare if can I cast safety the e.getSource() to JComboBox?
推荐答案
案例1:-
if(sourceObject.getClass()== JComboBox.class)是正确的处理方式比较起来,因为getClass()将返回sourceObject对象的运行时类,而JComboBox.class也将返回类
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
情况2:-
sourceObject.getClass()== JComboBox.class.getClass()会抛出不兼容的op-rend类型异常
case 2:-sourceObject.getClass() == JComboBox.class.getClass() it will throw incompatible op-rend type Exception
这篇关于我可以使用.getClass()== .class或.getClass()== .class.getClass()吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!