Я получаю исключение java.util.LinkedHashMap не может быть приведен к java.util.List на консоли - PullRequest
0 голосов
/ 10 апреля 2019

Метод класса контроллера

@RequestMapping(value="generics",method=RequestMethod.POST,produces="application/json",consumes="application/json")
public String generics(@RequestBody List<Object> objectlist) throws NoSuchFieldException, SecurityException, IOException
{
    System.out.println("controller:"+objectlist);
    return class1service.generics(objectlist);

}

Метод класса обслуживания`

 public String generics(List<Object> objectlist) throws NoSuchFieldException, SecurityException, IOException
    {
        System.out.println("service"+objectlist);
        return class1dao.generics(objectlist);
    }

Метод для проверки класса сущности частиц и вызова метода, который сгенерирует лист Excel для этих объектов

public String generics(List<?> clazz) throws IOException, NoSuchFieldException, SecurityException
{
    System.out.println("generics:"+clazz);
    try
    { 
    List<Class1> ll1=new ArrayList<Class1>();
    List<Class2> ll2=new ArrayList<Class2>();
    List<Class3> ll3=new ArrayList<Class3>();
    System.out.println("generics:"+clazz);
    System.out.println("in generics for loop");

            for (int i = 0; i < clazz.size(); i++)
            {

                System.out.println("in clazz loop");

                System.out.println("in clazz loop i:"+i);

                System.out.println("befor clazz.get(i)"+(clazz.get(i)));

                System.out.println("clazz instanceof List<?>"+(clazz instanceof List<?>));
                if (clazz instanceof List<?>)
                {

                    List<Class1>    a2=  (List<Class1>) clazz.get(i);
                    //ArrayList<Class1> a2=(ArrayList<Class1>) clazz.get(i);
                    Class1 c1=new Class1();
                    c1.setS1Id(((Class1) a2.get(i)).getS1Id());
                    System.out.println("c1.setS1Id(a1.get(i).getS1Id());"+ (((Class1) a2.get(i)).getS1Id()));
                    c1.setStudentName(((Class1) a2.get(i)).getStudentName());
                     System.out.println("c1.setS1Id(a1.get(i).getS1Id());"+ (((Class1) a2.get(i)).getStudentName()));
                     c1.setStudentAge(((Class1) a2.get(i)).getStudentAge());
                     System.out.println("c1.setS1Id(a1.get(i).getS1Id());"+ (((Class1) a2.get(i)).getStudentAge()));
                     c1.setEnglish(((Class1) a2.get(i)).getEnglish());
                     System.out.println("c1.setS1Id(a1.get(i).getS1Id());"+ (((Class1) a2.get(i)).getEnglish()));
                     c1.setKannada(((Class1) a2.get(i)).getKannada());
                     System.out.println("c1.setS1Id(a1.get(i).getS1Id());"+ (((Class1) a2.get(i)).getKannada()));
                     c1.setHindi(((Class1) a2.get(i)).getMathematics());
                     System.out.println("c1.setS1Id(a1.get(i).getS1Id());"+ (((Class1) a2.get(i)).getMathematics()));
                     c1.setScience(((Class1) a2.get(i)).getScience());
                     System.out.println("c1.setS1Id(a1.get(i).getS1Id());"+ (((Class1) a2.get(i)).getScience()));
                     c1.setSocielSience(((Class1) a2.get(i)).getSocielSience());
                     System.out.println("c1.setS1Id(a1.get(i).getS1Id());"+ (((Class1) a2.get(i)).getSocielSience()));
                     c1.setMathematics(((Class1) a2.get(i)).getMathematics());
                     System.out.println("c1.setS1Id(a1.get(i).getS1Id());"+ (((Class1) a2.get(i)).getMathematics()));
                     ll1.add(c1);
                     System.out.println("after clazz.get(i)"+(clazz.get(i)));
                     // ll1=(List<Class1>) a1;
                     System.out.println("ll1"+ll1);
                    listOfClass1(ll1);


                } 
                else if(clazz instanceof List<?>) {

                     List<Class2> a2=(List<Class2>) clazz.get(i);
                     Class2 c2=new Class2();
                     c2.setS2Id(a2.get(i).getS2Id());
                     c2.setStudentName(a2.get(i).getStudentName());
                     c2.setStudentAge(a2.get(i).getStudentAge());
                     c2.setEnglish(a2.get(i).getEnglish());
                     c2.setKannada(a2.get(i).getKannada());
                     c2.setHindi(a2.get(i).getMathematics());
                     c2.setScience(a2.get(i).getScience());
                     c2.setSocielSience(a2.get(i).getSocielSience());
                     c2.setMathematics(a2.get(i).getMathematics());
                     ll2.add(c2);
                     System.out.println("ll2"+ll2);
                    listOfClass2(ll2);
                }
                else if (clazz instanceof Class3)
                {
                     List<Class3> a3=(List<Class3>) clazz.get(i);
                     Class3 c3=new Class3();
                     c3.setS3Id(a3.get(i).getS3Id());
                     c3.setStudentName(a3.get(i).getStudentName());
                     c3.setStudentAge(a3.get(i).getStudentAge());
                     c3.setEnglish(a3.get(i).getEnglish());
                     c3.setKannada(a3.get(i).getKannada());
                     c3.setHindi(a3.get(i).getMathematics());
                     c3.setScience(a3.get(i).getScience());
                     c3.setSocielSience(a3.get(i).getSocielSience());
                     c3.setMathematics(a3.get(i).getMathematics());
                     ll3.add(c3);
                     System.out.println("ll3"+ll3);
                    listOfClass3(ll3);
                }
         }      
 return "added";
}
catch(Exception e)
{
    System.out.println(e.getMessage());
    return "not added";
}

}

Метод создания таблицы Excel для объектов класса Class1

 public void listOfClass1(List<Class1> stud1) throws IOException
 {
     System.out.println("listOfClass1:"+stud1);


     String[] columns = {"s1Id","studentName", "studentAge", "english","kannada","science","mathematics","socielScience","hindi","total","percentage","status"};  
        Workbook workbook = new XSSFWorkbook();
        CreationHelper createHelper = workbook.getCreationHelper();

        Sheet sheet = workbook.createSheet("class1");

          // Create a Font for styling header cells
        Font headerFont = workbook.createFont();
        headerFont.setBold(true);
        headerFont.setFontHeightInPoints((short) 14);
        headerFont.setColor(IndexedColors.RED.getIndex());

    // Create a CellStyle with the font
     CellStyle headerCellStyle = workbook.createCellStyle();
     headerCellStyle.setFont(headerFont);

    // Create a Row
     Row headerRow = sheet.createRow(0);
     System.out.println("");

    // Creating cells
     for(int i = 0; i < columns.length; i++)
     {
      Cell cell = headerRow.createCell(i);
      cell.setCellValue(columns[i]);
      cell.setCellStyle(headerCellStyle);
     }

     int rowCount = sheet.getLastRowNum();

    // FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();

    // CellReference cellReference = new CellReference("SUM(D2:E2:F2:G2:H2:I2)");
    // Row row = sheet.getRow(cellReference.getRow());
    // Cell cell = row.getCell(cellReference.getCol());
     int rowNum=1;
     int x=2;
     for(Class1 student1:stud1)
     {
     Row row = sheet.createRow(rowNum);

     row.createCell(0).setCellValue(student1.getS1Id());
     System.out.println(student1.getS1Id());
     row.createCell(1).setCellValue(student1.getStudentName());
    // CellValue cellValue = evaluator.evaluate(cell);
     row.createCell(2).setCellValue(student1.getStudentAge());

     row.createCell(3).setCellValue(student1.getEnglish());
     row.createCell(4).setCellValue(student1.getKannada());
     row.createCell(5).setCellValue(student1.getScience());
     row.createCell(6).setCellValue(student1.getMathematics());
     row.createCell(7).setCellValue(student1.getSocielSience());  
    // row.createCell(4, cellValue.getCellType());
     row.createCell(8).setCellValue(student1.getHindi());

     row.createCell(9).setCellFormula("SUM(D"+x+":E"+x+":F"+x+":G"+x+":H"+x+":I"+x+")");//.setCellValue(student1.getTotal());
     row.createCell(10).setCellFormula("((J"+x+")*100)/600");//student1.getPercentage());
     row.createCell(11).setCellValue(true);
     x++;
     rowNum++;
 }
 // Resize all columns to fit the content size
 for(int i = 0; i < columns.length; i++) {
     sheet.autoSizeColumn(i);
 }


 // Write the output to a file
///FileOutputStream fileOut = new FileOutputStream("excelone.xlsx");
String fileOut="C:/Users/Laxmi.Baragukar/Desktop/eclipse_neon/excelclass1.xlsx";

// return str;
//Base64.Encoder data=Base64.getEncoder().;
//String str=data.encodeToString(src)
 //String encode=fetching(fileOut);

 FileOutputStream fileOut1 = new FileOutputStream(fileOut);
 String encode=fetching(fileOut);
 workbook.write(fileOut1);
 fileOut1.close();
 workbook.close();


 //return fileOut;
}

Метод создания таблицы Excel для объектов класса Class2

public void listOfClass2(List<Class2> stud1) throws IOException
 {
     System.out.println("listOfClass2:"+stud1);


     String[] columns = {"s2Id","studentName", "studentAge", "english","kannada","science","mathematics","socielScience","hindi","total","percentage","status"};  
        Workbook workbook = new XSSFWorkbook();
        CreationHelper createHelper = workbook.getCreationHelper();

        Sheet sheet = workbook.createSheet("class1");

          // Create a Font for styling header cells
        Font headerFont = workbook.createFont();
        headerFont.setBold(true);
        headerFont.setFontHeightInPoints((short) 14);
        headerFont.setColor(IndexedColors.RED.getIndex());

    // Create a CellStyle with the font
     CellStyle headerCellStyle = workbook.createCellStyle();
     headerCellStyle.setFont(headerFont);

    // Create a Row
     Row headerRow = sheet.createRow(0);
     System.out.println("");

    // Creating cells
     for(int i = 0; i < columns.length; i++)
     {
      Cell cell = headerRow.createCell(i);
      cell.setCellValue(columns[i]);
      cell.setCellStyle(headerCellStyle);
     }

     int rowCount = sheet.getLastRowNum();

    // FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();

    // CellReference cellReference = new CellReference("SUM(D2:E2:F2:G2:H2:I2)");
    // Row row = sheet.getRow(cellReference.getRow());
    // Cell cell = row.getCell(cellReference.getCol());
     int rowNum=1;
     int x=2;
     for(Class2 student1:stud1)
     {
     Row row = sheet.createRow(rowNum);

     row.createCell(0).setCellValue(student1.getS2Id());
     System.out.println(student1.getS2Id());
     row.createCell(1).setCellValue(student1.getStudentName());
    // CellValue cellValue = evaluator.evaluate(cell);
     row.createCell(2).setCellValue(student1.getStudentAge());

     row.createCell(3).setCellValue(student1.getEnglish());
     row.createCell(4).setCellValue(student1.getKannada());
     row.createCell(5).setCellValue(student1.getScience());
     row.createCell(6).setCellValue(student1.getMathematics());
     row.createCell(7).setCellValue(student1.getSocielSience());  
    // row.createCell(4, cellValue.getCellType());
     row.createCell(8).setCellValue(student1.getHindi());

     row.createCell(9).setCellFormula("SUM(D"+x+":E"+x+":F"+x+":G"+x+":H"+x+":I"+x+")");//.setCellValue(student1.getTotal());
     row.createCell(10).setCellFormula("((J"+x+")*100)/600");//student1.getPercentage());
     row.createCell(11).setCellValue(true);
     x++;
     rowNum++;
 }
 // Resize all columns to fit the content size
 for(int i = 0; i < columns.length; i++) {
     sheet.autoSizeColumn(i);
 }


 // Write the output to a file
///FileOutputStream fileOut = new FileOutputStream("excelone.xlsx");
String fileOut="C:/Users/Laxmi.Baragukar/Desktop/eclipse_neon/excelclass2.xlsx";

// return str;
//Base64.Encoder data=Base64.getEncoder().;
//String str=data.encodeToString(src)
 //String encode=fetching(fileOut);

 FileOutputStream fileOut1 = new FileOutputStream(fileOut);
 String encode=fetching(fileOut);
 workbook.write(fileOut1);
 fileOut1.close();
 workbook.close();


 //return fileOut;
}

Метод создания таблицы Excel для объектов класса Class3

 public void listOfClass3(List<Class3> stud1) throws IOException
 {

     System.out.println("listOfClass3:"+stud1);
   /*List<Class3> class1=new ArrayList<Class3>();
   for(Class3 obj:stud1){
       Class3 c1=new Class3();
       c1.setS3Id(obj.getS3Id());
       c1.setStudentName(obj.getStudentName());
       c1.setStudentAge(obj.getStudentAge());
       class1.add(c1);
   }*/
     String[] columns = {"s3Id","studentName", "studentAge", "english","kannada","science","mathematics","socielScience","hindi","total","percentage","status"};  
        Workbook workbook = new XSSFWorkbook();
        CreationHelper createHelper = workbook.getCreationHelper();

        Sheet sheet = workbook.createSheet("class1");

          // Create a Font for styling header cells
        Font headerFont = workbook.createFont();
        headerFont.setBold(true);
        headerFont.setFontHeightInPoints((short) 14);
        headerFont.setColor(IndexedColors.RED.getIndex());

    // Create a CellStyle with the font
     CellStyle headerCellStyle = workbook.createCellStyle();
     headerCellStyle.setFont(headerFont);

    // Create a Row
     Row headerRow = sheet.createRow(0);
     System.out.println("");

    // Creating cells
     for(int i = 0; i < columns.length; i++)
     {
      Cell cell = headerRow.createCell(i);
      cell.setCellValue(columns[i]);
      cell.setCellStyle(headerCellStyle);
     }

     int rowCount = sheet.getLastRowNum();

    // FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();

    // CellReference cellReference = new CellReference("SUM(D2:E2:F2:G2:H2:I2)");
    // Row row = sheet.getRow(cellReference.getRow());
    // Cell cell = row.getCell(cellReference.getCol());
     int rowNum=1;
     int x=2;
     for(Class3 student1:stud1)
     {
     Row row = sheet.createRow(rowNum);

     row.createCell(0).setCellValue(student1.getS3Id());
     System.out.println(student1.getS3Id());
     row.createCell(1).setCellValue(student1.getStudentName());
    // CellValue cellValue = evaluator.evaluate(cell);
     row.createCell(2).setCellValue(student1.getStudentAge());

     row.createCell(3).setCellValue(student1.getEnglish());
     row.createCell(4).setCellValue(student1.getKannada());
     row.createCell(5).setCellValue(student1.getScience());
     row.createCell(6).setCellValue(student1.getMathematics());
     row.createCell(7).setCellValue(student1.getSocielSience());  
    // row.createCell(4, cellValue.getCellType());
     row.createCell(8).setCellValue(student1.getHindi());

     row.createCell(9).setCellFormula("SUM(D"+x+":E"+x+":F"+x+":G"+x+":H"+x+":I"+x+")");//.setCellValue(student1.getTotal());
     row.createCell(10).setCellFormula("((J"+x+")*100)/600");//student1.getPercentage());
     row.createCell(11).setCellValue(true);
     x++;
     rowNum++;
 }
 // Resize all columns to fit the content size
 for(int i = 0; i < columns.length; i++) {
     sheet.autoSizeColumn(i);
 }


 // Write the output to a file
///FileOutputStream fileOut = new FileOutputStream("excelone.xlsx");
String fileOut="C:/Users/Laxmi.Baragukar/Desktop/eclipse_neon/excelclass3.xlsx";

// return str;
//Base64.Encoder data=Base64.getEncoder().;
//String str=data.encodeToString(src)
 //String encode=fetching(fileOut);

 FileOutputStream fileOut1 = new FileOutputStream(fileOut);
 String encode=fetching(fileOut);
 workbook.write(fileOut1);
 fileOut1.close();
 workbook.close();


 //return fileOut;
}

Я отправляю список объектов класса сущностей из postman.if я нажимаю Объект сущности Class1 затем проверит и сгенерирует лист Excel для Сущность Class1 или, если я нажму объект сущности class2, он проверит и сгенерировать лист Excel для объекта Class2 Object.

1 Ответ

0 голосов
/ 10 апреля 2019

Пожалуйста, обновите ваш вопрос.Он содержит слишком много кода, большая часть которого не имеет отношения к вопросу.

Как правило, вы не можете приводить из LinkedHashMap в List (или наоборот).Что вы можете сделать, это:

public static <V, K> void main(String[] args) {
    LinkedHashMap<K,V> map = new LinkedHashMap<K, V>();
    List<K> keyList = new ArrayList<>(map.keySet());
    List<V> valueList = new ArrayList<>(map.values());
}

(я не уверен, что это то, что вы ищете. Я не прочитал весь код.)

...