Exception in thread "AWT-Eventqueue-0" java.lang.Classcastexception: [Ljava.lang.Object; cannot be cast to [Lbr.com.jcom.modelo.Brand;

Asked

Viewed 754 times

-1

I’m making the following mistake :

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Lbr.com.jcom.modelo.Marca;
    at br.com.jcom.dao.MarcaDao.insert(MarcaDao.java:1)
    at br.com.jcom.facade.DaoFacade.insert(DaoFacade.java:21)
    at br.com.jcom.controller.MarcaController.addMarca(MarcaController.java:19)
    at br.com.jcom.gui.MarcaGUI$3.actionPerformed(MarcaGUI.java:145)
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$500(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

It’s just, when I do the Insert straight through MarcaDAO:

MarcaDao marcadao = new MarcaDao();
marcadao.insert(marca);

Works normally.

But when I walk by controller, which passes into the Façade, presents the above error:

int result = 0;

                if (idMarca == null) {
                    System.out.println("ADD");
                    result = new MarcaController().addMarca(marca);
                } else {
                    marca.setMarcaID(idMarca);
                    result = new MarcaController().updateMarca(marca);
                    idMarca = null;
                }

So the mistake doesn’t make MarcaDAO.

I went up the project in the mega, for anyone who can help me take a look. It has the database in Sqlserver 2005 as well.

link: https://mega.co.nz/#! Pp1kgahl! e7G1NF6T6zcMPKAdZlHof8Eyw48fppR_SsFJY-2Zw7M

MarcaDao:

package br.com.jcom.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import br.com.jcom.factory.Conexao;
import br.com.jcom.modelo.Marca;

public class MarcaDao implements IDao<Marca> {

    private String nomeTabela = "Marcas";
    private Connection connection;

    public MarcaDao() {
        this.connection = new Conexao().getConnection();

    }

    @Override
    public String getNomeTabela() {
        return nomeTabela;
    }

    @Override
    public int insert(Marca... elementos) {

        String sql = "INSERT INTO " + nomeTabela + " (marca) VALUES (?)";
        PreparedStatement stmt = null;
        int result = 0;

        for (Marca marca : elementos) {
            try {
                stmt = connection.prepareStatement(sql);
                stmt.setString(1, marca.getMarca());
                result = stmt.executeUpdate();

            } catch (SQLException e) {
                throw new RuntimeException(e);
            } finally{
                Conexao.close(connection, stmt, null);
            }
        }

        return result;
    }

    @Override
    public int update(Marca... elementos) {

        String sql = "UPDATE " + nomeTabela + "SET marca = ? WHERE MarcaID = ?";
        PreparedStatement stmt = null;
        int result = 0;

        for (Marca marca : elementos) {
            try {
                stmt = connection.prepareStatement(sql);
                stmt.setString(1, marca.getMarca());
                stmt.setLong(2, marca.getMarcaID());
                result = stmt.executeUpdate();

            } catch (SQLException e) {
                throw new RuntimeException(e);
            } finally {
                Conexao.close(connection, stmt, null);
            }
        }

        return result;
    }

    @Override
    public int delete(Marca... elementos) {

        String sql = "DELETE FROM " + nomeTabela + "WHERE MarcaID = ?";
        PreparedStatement stmt = null;
        int result = 0;

        for (Marca marca : elementos) {
            try {
                stmt = connection.prepareStatement(sql);
                stmt.setLong(1, marca.getMarcaID());
                result = stmt.executeUpdate();

            } catch (SQLException e) {
                throw new RuntimeException(e);
            } finally {
                Conexao.close(connection, stmt, null);
            }
        }

        return result;
    }

    @Override
    public List<Marca> selectAll() {
        String sql = "SELECT * FROM " + nomeTabela;
        PreparedStatement stmt = null;
        List<Marca> marcas = new ArrayList<Marca>();
        ResultSet rs = null;

        try {
            stmt = connection.prepareStatement(sql);
            rs = stmt.executeQuery();

            while (rs.next()) {
                Marca marca = new Marca();
                marca.setMarcaID(rs.getLong("marcaID"));
                marca.setMarca(rs.getString("marca"));

                marcas.add(marca);

            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            Conexao.close(connection, stmt, rs);
        }
        return marcas;

    }

}

IDao:

package br.com.jcom.dao;

import java.util.List;

public interface IDao<T> {

    String getNomeTabela();

    int insert(T... elementos);

    int update(T... elementos);

    int delete(T... elementos);

    //T selectCodigo(String codigo);

    //T select(String sql, String... paramentros);

    List<T> selectAll();

    // List<T> selectAll(String sql, String... paramentros);

}

DaoFacade:

package br.com.jcom.facade;

import java.util.List;

import br.com.jcom.dao.IDao;
import br.com.jcom.modelo.Marca;

public class DaoFacade<T> {
    @SuppressWarnings("rawtypes")
    private IDao dao;

    public DaoFacade(IDao dao) {
        this.dao = dao;

    }

    @SuppressWarnings("unchecked")
    public int insert(Marca marca) {
        return dao.insert(marca);

    }

    @SuppressWarnings("unchecked")
    public int update(T... elementos) {
        return dao.update(elementos);

    }

    @SuppressWarnings("unchecked")
    public int delete(T... elementos) {
        return dao.delete(elementos);

    }

    @SuppressWarnings("unchecked")
    public List<T> selectAll() {
        return dao.selectAll();

    }

}

Marca (model):

package br.com.jcom.modelo;

public class Marca {

    private Long marcaID;
    private String marca;

    public Marca() {
        super();
    }

    public Marca(Long marcaID, String marca) {
        super();
        this.marcaID = marcaID;
        this.marca = marca;
    }

    public Long getMarcaID() {
        return marcaID;
    }

    public void setMarcaID(Long marcaID) {
        this.marcaID = marcaID;
    }

    public String getMarca() {
        return marca;
    }

    public void setMarca(String marca) {
        this.marca = marca;
    }

}

MarcaController:

package br.com.jcom.controller;

import java.util.List;

import br.com.jcom.dao.MarcaDao;
import br.com.jcom.facade.DaoFacade;
import br.com.jcom.modelo.Marca;

public class MarcaController {

    private DaoFacade marcaFacade;

    public MarcaController() {
        this.marcaFacade = new DaoFacade<Marca>(new MarcaDao());
    }

    public int addMarca(Marca marca) {
        return marcaFacade.insert(marca);

    }

    public int updateMarca(Marca marca) {
        return marcaFacade.update(marca);

    }

    public int deleteMarca(Marca marca) {
        return marcaFacade.delete(marca);

    }

    public List<Marca> selectMarcas() {
        return marcaFacade.selectAll();

    }

}

Calling for MarcaGUI save button:

btnSalvar.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Marca marca = new Marca();

            if (Funcoes.validaCampos(panel) == true) {
                marca.setMarca(tfMarca.getText());
            } else {
                JOptionPane.showMessageDialog(null,
                        "Preenchimento de campos (*) obrigatórios");
                return;
            }

            int result = 0;

            if (idMarca == null) {
                new MarcaController().addMarca(marca);
            } else {
                marca.setMarcaID(idMarca);
                result = new MarcaController().updateMarca(marca);
                idMarca = null;
            }

            if (result == 1) {
                JOptionPane.showMessageDialog(null, "Concluido");
            } else {
                JOptionPane.showMessageDialog(null, "Erro ao salvar");
            }

            refreshTable();
        }
    });
}
  • Post the FACADE, with the constructor and the Insert method, the Marcadao’s Insert method and how it is creating its instances.

  • I edited the post..

1 answer

4


Whenever there’s a warning, something doesn’t go right in the code, in your case Piler tried to warn you but you ignored. Your problem is varargs with generics, That one varargs of the parameter is converted to a array de Object, that fails in the cast for Mark and results in ClassCastException. That article has a detailed account and explanation.

Conclusion: It is probably best to avoid providing Objects of non-reifiable types Where a variable argument list is expected. You will Always receive an unchecked Warning and unless you know Exactly what the Invoked method does you can Never be sure that the Invocation is type-safe.


Conclusion: It is probably best to avoid providing objects type non-reifiable where a list of arguments is expected variable. You will always receive a warning and if you do not know exactly what the summoner method does, you can never be sure that the invocation is safe.

  • OK, but what VC recommends to do then?

  • how should I do then?

  • well I think I understand, replace: "int Insert(T... elements);" by: "int Insert(T elements);"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.