kdn
kdn

Reputation: 195

Java - instanceof returning false when should be true

So basically, im implementing interface in a view, then pass the view as source of custom event, in one of 3 "instanceof" calls it return false.

View:

public class NamedOffensiveStatsView extends BagVectorPanel implements INamedOffensiveStatsView {

Event.toString():

@Override
public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append(this.getSource().getClass() + ": ");

e.toString() prints:

class pl.drag0nius.diablo3.DPSCalc.NamedOffensiveStats.NamedOffensiveStatsView$2

instanceof returning false:

@Override
public void eventFired(Event e) {
    logger.debug("eventFired: " + e.toString());
    if (e.getSource() instanceof INamedOffensiveStatsView) {

Also i cannot cast from view to it's interface.

Answer:

With help of my friend we found the issue.

The code calling event (inside initComponents() of view):

    jComboBox.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (comboBoxReady) {
                logger.debug("actionPerformed");
                listener.eventFired(new Event(this, "selection", jComboBox.getSelectedIndex()));
            }
        }
    });

What it should be:

    jComboBox.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (comboBoxReady) {
                logger.debug("actionPerformed");
                listener.eventFired(new Event(NamedOffensiveStatsView.this, "selection", jComboBox.getSelectedIndex()));
            }
        }
    });

"this" was referencing nested class, not the view.

Upvotes: 2

Views: 3044

Answers (1)

akf
akf

Reputation: 39485

the $2 at the end of the classname indicates that the source seems to be an anonymous innerclass of NamedOffensiveStatsView. It therefore would not be an instance of NamedOffensiveStatsView

Upvotes: 8

Related Questions