首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何解决 Java - JSP Wrong Class Cast?

如何解决 Java - JSP Wrong Class Cast?
EN

Stack Overflow用户
提问于 2018-08-02 01:15:43
回答 1查看 0关注 0票数 0

我有一个非常奇怪的错误,似乎是JSPRuntime或反射API的一个错误,以下是我的代码:

代码语言:txt
复制
public class LB {
    private ArrayList<Class> classes = new ArrayList<>();
    public ArrayList<Class> getClasses() {
        return classes;
    }
    public void setClasses(ArrayList<Class> classes) {
        this.classes = classes;
    }
}


public enum Class {
    EINSBHIT("1BHIT"),
    EINSAHIT("1AHIT"),
    ZWEIBHIT("2BHIT"),
    ZWEIAHIT("2AHIT"),
    DREIBHIT("3BHIT"),
    DREIAHIT("3AHIT");
    private final String id;
    private Class(String id) {
        this.id = id;
    }
    public String getId() {
        return id;
    }
    @Override
    public String toString() {
        return id;
    }
    public static Class getByName(String name) {
        for (Class c : values())
            if(c.getId().equals(name))
                return c;
        return null;
    }
}

所以我有一个JSP页面,需要ArrayList:

代码语言:txt
复制
ArrayList<LB> dayLbs = LBManager.getDayLbs(d);
for(LB lb : dayLbs){
    System.out.println("Entry Class : "lb.getClasses().get(0).getClass());
    ArrayList<Class> classes = lb.getClasses();
    for(Object c : classes){
        System.out.println("Entry class : "+c.getClass());
    }
} 

And honestly this code doesnt makes sense right? Yes you are right! But listen why i changed the code to this.

代码的输出如下:

代码语言:txt
复制
List Class : class java.util.ArrayList
Entry class : class java.lang.String
Entry class : class java.lang.String
Entry class : class java.lang.String
List Class : class java.util.ArrayList
Entry class : class java.lang.String
Entry class : class java.lang.String

如果我写:for(Class c : classes){虽然没有出现编译器错误,但是如果我调用页面,就会得到:

代码语言:txt
复制
    org.apache.jasper.JasperException: An exception occurred processing JSP page /assets/comps/eintragung.jsp at line 66

    63:             lbloop:for(LB lb : dayLbs){
    64:                 System.out.println("List Class : "+lb.getClasses().getClass());
    65:                 ArrayList<Class> classes = lb.getClasses();
    66:                 for(Class c : classes){
    67:                     System.out.println("Entry class : "+c.getClass());
    68:                     if(c.toString().equals(css.getId())){
    69: java.lang.ClassCastException: java.lang.String cannot be cast to com.lb.logic.Class
        org.apache.jsp.assets.comps.eintragung_jsp._jspService(eintragung_jsp.java:24

2)

该如何解决呢?

代码语言:txt
复制
<%@page import="java.io.IOException"%>
<%@page import="com.lb.logic.student.DayPlan"%>
<%@page import="com.lb.logic.student.WeekPlan"%>
<%@page import="com.lb.utilitys.TimeManager"%>
<%@page import="com.lb.threads.EMailSenderSceduler"%>
<%@page import="com.lb.utilitys.LBManager"%>
<%@page import="com.lb.logic.lb.LB"%>
<%@page import="com.lb.logic.student.Student"%>
<%@page import="com.lb.inet.logic.CookieManager"%>
<%@page import="com.lb.logic.Lesson"%>
<%@page import="java.io.File"%>
<%@page import="java.io.FileFilter"%>
<%@page import="com.niton.media.filesystem.Directory"%>
<%@page import="java.util.ArrayList"%>
<%@page import="de.codeschnipsel.simple.mail.Email"%>
<%@page import="java.util.Locale"%>
<%@page import="com.lb.logic.Day"%>
<%@page import="java.util.Calendar"%>
<%@page import="java.util.GregorianCalendar"%>
<%@page import="com.lb.logic.Class"%>
<%@page import="com.lb.inet.logic.AccountManager"%>
<%
    System.out.println("Eintragung.jsp request");
    request.setCharacterEncoding("UTF-8");
%>
<%
    Student s = CookieManager.getSession(request);
    if (s == null) {
        System.out.println("Redirect : 25");
        response.sendRedirect("index.jsp?page=login&msg=Anmeldungs-cookie%20ungültig!");
%>
        <meta http-equiv="refresh" content="0; url=index.jsp?page=login&msg=Anmeldungs-cookie%20ungültig!">
<%
        return;
    } else {
        Class css = s.getSchoolClass();
        if (request.getParameter("msg") != null)
            out.print("<script>alert(\"" + request.getParameter("msg") + "\");</script>");
%>
<div id="daybox">
    <form action="Writer" method="post">
        <%
        request.setCharacterEncoding("UTF-8");
        Day today = Day.getToday();
        ArrayList<LB> todayLbs = LBManager.getTodayLbs();
        boolean lbLeft = false;
        int mins = TimeManager.getMinutesTill8();
        for (LB l : todayLbs) {
            if (!(l.getTable().getLessons(today).get(0).from - EMailSenderSceduler.minsBevore < mins)) {
                lbLeft = true;
            }
        }
        int index = today.getIndex();
        WeekPlan studentsPlan = s.getThisWeek(); 
        for (int i = 0; i < Day.SATURDAY.getDaysAfter().size(); i++) {
            Day d = Day.SATURDAY.getDaysAfter().get(i);
            DayPlan dayPlan = studentsPlan.get(d);
            if (d == Day.SATURDAY || d == Day.SUNDAY) {
                continue;
            }
            ArrayList<LB> dayLbs = LBManager.getDayLbs(d);
            ArrayList<LB> dayClassLBs = new ArrayList<>();
            lbloop:for(LB lb : dayLbs){
                System.out.println("List Class : "+lb.getClasses().getClass());
                ArrayList<Class> classes = lb.getClasses();
                for(Class c : classes){
                    System.out.println("Entry class : "+c.getClass());
                    if(c.toString().equals(css.getId())){
                        dayClassLBs.add(lb);
                        continue lbloop;
                    }
                }
            }
        %>
        <div class="day">
            <h1><%=d.name%></h1>
            <h2>Vormittag</h2>
            <h2>Nachmittag</h2>
            <br> <span> <%
                Calendar cal = GregorianCalendar.getInstance();
                if (!lbLeft) {
                    cal.set(Calendar.DAY_OF_YEAR, (cal.get(Calendar.DAY_OF_YEAR) - index));
                }
                cal.set(Calendar.DAY_OF_YEAR, (cal.get(Calendar.DAY_OF_YEAR) + i));
                out.print(cal.get(Calendar.DAY_OF_MONTH) + "." + (cal.get(Calendar.MONTH) + 1) + "."
                + cal.get(Calendar.YEAR));
 %>
            </span>
            <select name="<%=d.name%>-morning">
            <%

                //Der Tag der momentanen Schleife ist vor heute -> nicht änderbar
                boolean done = false;
                if(d.isBevore(today)){
                    writeOverLB(dayPlan, dayClassLBs, out, d,false);
                    done = true;
                }else{
                    //Der tag kommt noch eintragungsmöglichkeit
                    if(d == today){
                        int noonLBstart = 250;
                        for(LB lb : dayClassLBs)
                            if(lb.getTable().getLessons(d).get(0).from < 250){
                                noonLBstart = lb.getTable().getLessons(d).get(0).from;
                            }
                        if(noonLBstart-EMailSenderSceduler.minsBevore < TimeManager.getMinutesTill8()){
                            writeOverLB(dayPlan, dayClassLBs, out, d,true);
                            done = true;
                        }
                    }
                    if(!done){

            %>
                <option value="none">Nicht Eingetragen</option>
                <%
                        for (LB lb : dayClassLBs) {
                            if (lb.getTable().getLessons(d).get(0).from < 250) {
                                boolean isIn = false;
                                for (Student sx : lb.getCurrentWeek().getRegistrations(d)) {
                                    if (sx.getName().equals(s.getName()))
                                        isIn = true;
                                }
                                out.print("<option value=\"" + lb.getName() + "\" "
                                            + (isIn ? "selected=\"selected\"" : "") + ">" + lb.getSubject().getName()
                                        + " - " + lb.getTeacher().name.split(" ")[1] + " "
                                        + lb.getCurrentWeek().getRegistrations(d).size() + "/" + lb.getCapacity() + "</option>");
                            }
                        }
                    }
                }
            %>
            </select>
            <select name="<%=d.name%>-afternoon">
            <%

                //Der Tag der momentanen Schleife ist vor heute -> nicht änderbar
                if(d.isBevore(today)){
                    if(dayPlan.getAfterNoonLb().equals("none"))
                        out.print("<option selected=\"selected\"> Nicht eingetragen </option>");
                    else{
                        writeOverLB(dayPlan, dayClassLBs, out, d,false);
                    }
                    done = true;
                }else{
                    //Der tag kommt noch eintragungsmöglichkeit
                    if(d == today){
                        int afternoonLBstart = 250;
                        for(LB lb : dayClassLBs)
                            if(lb.getTable().getLessons(d).get(0).from > 230){
                                afternoonLBstart = lb.getTable().getLessons(d).get(0).from;
                            }
                        if(afternoonLBstart-EMailSenderSceduler.minsBevore < TimeManager.getMinutesTill8()){
                            writeOverLB(dayPlan, dayClassLBs, out, d,false);
                            done = true;
                        }
                    }
                    if(!done){

            %>
                <option value="none">Nicht eingetragen</option>
                <%
                        for (LB lb : dayClassLBs) {
                            if (lb.getTable().getLessons(d).get(0).from > 250) {
                                boolean isIn = false;
                                for (Student sx : lb.getCurrentWeek().getRegistrations(d)) {
                                    if (sx.getName().equals(s.getName()))
                                        isIn = true;
                                }
                                out.print("<option value=\"" + lb.getName() + "\" "
                                            + (isIn ? "selected=\"selected\"" : "") + ">" + lb.getSubject().getName()
                                        + " - " + lb.getTeacher().name.split(" ")[1] + " "
                                        + lb.getCurrentWeek().getRegistrations(d).size() + "/" + lb.getCapacity() + "</option>");
                            }
                        }
                    }
                }
            %>
            </select>

        </div>
        <%
            }
        %>
        <input type="submit" value="Eintragen">
    </form>
</div>
<%
    }
%>


<%!
    public void writeOverLB(DayPlan dayPlan,ArrayList<LB> dayClassLBs,JspWriter out,Day d,boolean noon) throws IOException{
        if(dayPlan.getNoonLb().equals("none"))
            out.print("<option selected=\"selected\"> Nicht eingetragen </option>");
        else{
            LB lb = null;
            for(LB dclb : dayClassLBs)
                if(dclb.getName().equals(noon ? dayPlan.getNoonLb() : dayPlan.getAfterNoonLb()))
                    lb = dclb;
            if(lb == null){
                out.print("<option value=\"" + lb.getName() + "\" "
                        + "selected=\"selected\">" + (noon ? dayPlan.getNoonLb() : dayPlan.getAfterNoonLb()) + "</option>");
            }else
            out.print("<option value=\"" + lb.getName() + "\" "
                + "selected=\"selected\">" + lb.getSubject().getName()
                + " - " + lb.getTeacher().name.split(" ")[1] + " "
                + lb.getCurrentWeek().getRegistrations(d).size() + "/" + lb.getCapacity() + "</option>");
        }
    }       

%>






package com.lb.utilitys;

import java.util.ArrayList;

import com.lb.logic.Day;
import com.lb.logic.lb.LB;
import com.niton.media.filesystem.Directory;

public class LBManager {
    private static ArrayList<LB> lbs;

    public static ArrayList<LB> getAllLbs() {
        if (lbs == null)
            readAllLbs();
        return lbs;
    }
    private static void readAllLbs() {
        try {
            Directory d = new Directory(System.getProperty("user.home")).addAndSaveDir("lbs");
            ArrayList<Directory> all = d.getSubFolder();
            lbs = new ArrayList<>();
            for (Directory directory : all) {
                LB lb = LB.read(directory);
                lbs.add(lb);
            }
        } catch (Exception e) {
            Log.log(e, "Fehler beim lesen der Lernbüros");
        }
    }

    /**
     * Filtert alle LBs von Heute Aus dem Array und gibt die Richtigen als
     * {@link ArrayList} zurück
     * 
     * @param all
     *            die Lernbüros aus denen die heutigen gefiltert werden sollen
     * @return die Heutigen Lernbüros
     */
    public static ArrayList<LB> getTodayLbs() {
        return getDayLbs(TimeManager.getToday());
    }

    /**
     * Filtert alle LBs von D Aus dem Array und gibt die Richtigen als
     * {@link ArrayList} zurück
     * 
     * @param d
     *            der zu filterte Tag
     * @return die an diesem Tag stattfindenden Lernbüros
     */
    public static ArrayList<LB> getDayLbs(Day d) {
        ArrayList<LB> today = new ArrayList<>();
        for (LB lb : lbs) {
            if (lb.getTable().getLessons(d).size() > 0)
                today.add(lb);
        }
        return today;
    }


    public static void saveAll() {
        for (LB lb : lbs) {
            try {
                lb.save(new Directory(System.getProperty("user.home")));
            } catch (Exception e) {
                Log.log(e, "Error during saving LB");
            }
        }
    }
    public static LB getLB(String name) {
        for (LB lb : lbs)
            if(lb.getName().equals(name))
                return lb;
        return null;
    }

}





package com.lb.logic.lb;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;

import com.lb.logic.Class;
import com.lb.logic.Subject;
import com.lb.logic.Teacher;
import com.niton.media.crypt.SimpleAES;
import com.niton.media.filesystem.Directory;
import com.niton.media.filesystem.NFile;
import com.niton.media.json.JsonArray;
import com.niton.media.json.JsonObject;

/**
 * Eine Klasse die ein Lernbüro repräsentiert<br>
 * sie speichert die einzelnen Stundenblöcke und die dafür eingetragenen
 * Schüler!
 * 
 * @author NilsBrugger, Max Frühmann
 * @serial Serializable
 */
public class LB {
    public static LB read(Directory parent) throws IOException, ClassNotFoundException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        LB lb = new LB();


        readData(parent,lb);
        readTimetable(parent,lb);

        NFile keyFile = new NFile(parent, "key", "store");
//      SecretKey key = (SecretKey) keyFile.readData();
//      keyFile.getInputStream().close();
//      keyFile.delete();
        SecretKey key = null;
        readCurrent(parent,lb,key);
        readOldRegistrations(parent,lb,key);

        return lb;
    }
    private static void readCurrent(Directory d, LB lb, SecretKey key) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, ClassNotFoundException, BadPaddingException, IOException {
        NFile cur = new NFile(d, "current", "data");
//      lb.setCurrentWeek((WeekRegistrations) SimpleAES.decryptObject((SealedObject) cur.readData(), key));
        lb.setCurrentWeek((WeekRegistrations) cur.readData());

    }
    private static void readData(Directory d, LB lb) throws IOException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        NFile dataFile = new NFile(d, "data", "json");
        JsonObject data = (JsonObject) dataFile.readJson();
        data.read(lb);
    }
    private static void readOldRegistrations(Directory d, LB lb, SecretKey key) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, ClassNotFoundException, BadPaddingException, IOException {
        d = d.addDir("old");
        ArrayList<WeekRegistrations> weeks = new ArrayList<>();
        for (NFile weekRegistration : d.getSubFiles()) {
            if(weekRegistration.getAbsolutePath().endsWith(".data")) {
//              weeks.add((WeekRegistrations) SimpleAES.decryptObject((SealedObject) weekRegistration.readData(), key));
                weeks.add((WeekRegistrations) weekRegistration.readData());
            }
        }
        lb.setWeeks(weeks);
    }
    @SuppressWarnings("unchecked")
    private static void readTimetable(Directory d, LB lb) throws IOException, ClassNotFoundException {
        NFile tableFile = new  NFile(d, "timetable", "json");
        Timetable tt = new Timetable();
        tt.read((JsonArray<JsonObject>) tableFile.readJson());
        lb.setTable(tt);
    }
    /**
     * Der gegenstand der unterrichtet wird
     */
    private Subject subject;
    /**
     * Maximale Kapazität des Raumes
     */
    private int capacity = 20;
    /**
     * Der Lehrer der dieses LB betreuen wird
     */
    private Teacher teacher;

    /**
     * Klassen mit Zugriff auf dieses Lernbüro
     */
    private ArrayList<Class> classes = new ArrayList<>();

    private transient Timetable table;

    private transient ArrayList<WeekRegistrations> weeks = new ArrayList<>();

    private transient WeekRegistrations currentWeek = new WeekRegistrations();

    private String name;

    public int getCapacity() {
        return capacity;
    }

    public ArrayList<Class> getClasses() {
        return classes;
    }

    public WeekRegistrations getCurrentWeek() {
        return currentWeek;
    }

    public String getName() {
        return name;
    }

//  public ArrayList<Student> getStudentsFor(Day d) {
//      if (d == null)
//          return null;
//      switch (d) {
//      case FRIDAY:
//          return getStudentsOnFr();
//      case MONDAY:
//          return getStudentsOnMo();
//      case THUESDAY:
//          return getStudentsOnDi();
//      case THURESDAY:
//          return getStudentsOnDo();
//      case WEDNESDAY:
//          return getStudentsOnMi();
//      case SATURDAY:
//      case SUNDAY:
//          return new ArrayList<>();
//      default:
//          return null;
//      }
//  }

    public Subject getSubject() {
        return subject;
    }

    public Timetable getTable() {
        return table;
    }

    public Teacher getTeacher() {
        return teacher;
    }

    public ArrayList<WeekRegistrations> getWeeks() {
        return weeks;
    }

    public void save(Directory parent) throws Exception {
        Directory d = parent.addAndSaveDir("lbs").addAndSaveDir(getName());

        saveData(d);
        saveTimetable(d);

        SecretKey key = SimpleAES.generateKey(128);
        NFile keyFile = new NFile(d, "key", "store");
        keyFile.save();
        keyFile.write(key);

        saveCurrent(d,key);

        saveOldRegistrations(d,key);
    }

    private void saveCurrent(Directory d,SecretKey key) throws IOException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException {
        NFile cur = new NFile(d, "current", "data");
//      cur.write(SimpleAES.encryptObject(currentWeek, key));
        cur.write(currentWeek);
    }

    private void saveData(Directory d) throws Exception {
        NFile dataFile = new NFile(d, "data", "json");
        if(dataFile.exisits())
            dataFile.delete();
        dataFile.save();

        JsonObject data = new JsonObject(this);
        dataFile.write(data);
    }
    private void saveOldRegistrations(Directory d, SecretKey key) throws IOException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException {
        d = d.addAndSaveDir("old");
        int i = 0;
        for (WeekRegistrations weekRegistrations : weeks) {
            NFile nf = new NFile(d, "School Week "+i, "data");
//          nf.write(SimpleAES.encryptObject(weekRegistrations,key));
            nf.write(weekRegistrations);
        }
    }

    private void saveTimetable(Directory d) throws IOException {
        NFile tableFile = new  NFile(d, "timetable", "json");
        if(tableFile.exisits())
            tableFile.delete();
        tableFile.write(table.getJSON());
    }

    public void setCapacity(int capacity) {
        this.capacity = capacity;
    }

    public void setClasses(ArrayList<Class> classes) {
        this.classes = classes;
    }

    public void setCurrentWeek(WeekRegistrations currentWeek) {
        this.currentWeek = currentWeek;
    }
    public void setName(String name) {
        this.name = name;
    }

    public void setSubject(Subject subject) {
        this.subject = subject;
    }

    public void setTable(Timetable table) {
        this.table = table;
    }

    public void setTeacher(Teacher teacher) {
        this.teacher = teacher;
    }

    public void setWeeks(ArrayList<WeekRegistrations> weeks) {
        this.weeks = weeks;
    }
    public void newWeek() {
        weeks.add(currentWeek);
        currentWeek = new WeekRegistrations();
    }

}
EN

回答 1

Stack Overflow用户

发布于 2018-08-02 10:35:20

如果你把它改为for(Class c : classes),那么在这种情况下也应该将其更改为c.getId(),还有为什么要用c.toString()?应该用c.name()吧

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100001856

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档