简体   繁体   English

Java:ClassCastException-无法将java.lang.Class强制转换为

[英]Java: ClassCastException - java.lang.Class cannot be cast to

So I get a, 所以我得到了

ClassCastException: java.lang.Class cannot be cast to com.glostrode.Management.Link ClassCastException:无法将java.lang.Class强制转换为com.glostrode.Management.Link

The line on which the exception occurs on the line indicated in the following method (line 32 of the file): 在以下方法(文件的第32行)中指示的行上,发生异常的行:

public Link getLink(String name) {
    txtFile f = new txtFile("plugins/PrimeManager/linksList.txt");
    List<String> lines = f.getLines();
    int i;
    txtFile f2;
    for(i=0; i<lines.size(); i++){
        f2 = new txtFile("plugins/PrimeManager/links/"+lines.get(i)+".txt");
        if(f2.getLines().isEmpty()) {
            return null;
        }
        Object o = f2.getObject();
        Link li = (Link) o;// THIS LINE HERE
        if(li.name == lines.get(i)){
            return li;
        }
    }
    return null;
}

The getLines() method returns a List<String> containing the lines in the file specified in the initialisation of the txtFile object. getLines()方法返回一个List<String>其中包含在txtFile对象的初始化中指定的文件中的行。 The getObject() method is as follows: getObject()方法如下:

public Object getObject(){
        try {
            FileInputStream i = new FileInputStream(this.file);
            ObjectInputStream o = new ObjectInputStream(i);
            Object r = o.readObject();
            o.close();
            i.close();
            return r;
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}

From my current understanding, the object returned by o.readObject() should be castable to its original form (the file that is read contains a Link object). 根据我目前的理解,由o.readObject()返回的对象应该可转换为其原始形式(读取的文件包含Link对象)。

I used the following method to add it to the file: 我使用以下方法将其添加到文件中:

public void addObject(Object obj){
    try {
        FileOutputStream f = new FileOutputStream(this.file);
        ObjectOutputStream o = new ObjectOutputStream(f);
        o.writeObject(obj);
        o.flush();
        o.close();
        f.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

txtFile constructor: txtFile构造函数:

public txtFile(String path) {
        this.path = path;
        this.file = new File(path);
        if(!this.file.exists()){
            try {
                this.file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

The source code: linksCommand.java: 源代码:linksCommand.java:

package com.glostrode.Management;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;

import com.glostrode.Management.FileIO.txtFile;
//import com.glostrode.Management.FileIO.txtFile;


public class linksCommand implements CommandExecutor {

    public Link getLink(String name) {
        txtFile f = new txtFile("plugins/PrimeManager/linksList.txt");
        List<String> lines = f.getLines();
        int i;
        txtFile f2;
        for(i=0;i<lines.size();i++){
            f2 = new txtFile("plugins/PrimeManager/links/"+lines.get(i)+".txt");
            if(f2.getLines().isEmpty()) {
                return null;
            }
            Link li = f2.getObject() != null ? (Link) f2.getObject() : null;
            if(li.name == lines.get(i)){
                return li;
            }
        }
        return null;
    }
    public List<String> getLinks() {
        int i;
        List<String> a = new ArrayList<String>();
        txtFile f = new txtFile("plugins/PrimeManager/linksList.txt");
        if(f.getLines().isEmpty()){
            return null;
        }
        for(i=0;i<f.getLines().size();i++){
            Link b = this.getLink(f.getLines().get(i));
            if(b!=null) {
                a.add(b.name+": "+b.link);
            }
        }
        return a;
    }
    public void addLink(Link l){
        txtFile f = new txtFile("plugins/PrimeManager/linksList.txt");
        f.addLine(l.name);
        txtFile lf = new txtFile("plugins/PrimeManager/links/"+l.name+".txt");
        lf.addObject(l.getClass());
    }
    public void deleteLink(String name){
        txtFile f = new txtFile("plugins/PrimeManager/links/"+name+".txt");
        f.delete();
    }
    public void exists() throws IOException{
        File f = new File("plugins/PrimeManager/links.json");
        if(!(f.exists())){
            f.createNewFile();
            BufferedWriter w = new BufferedWriter(new FileWriter(f));
            w.write("[{\"name\":\"example\",\"link\":\"https://www.google.com/\"}]");
            w.flush();
            w.close();
        }
    }

    public linksCommand() {
    }

    @Override
    public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
        if(args.length>0 || (args.length != 0 && args[0] == null)){
            Link a = (Link)this.getLink(args[0]);
            if(a==null){
                sender.sendMessage(ChatColor.RED+"Link not found!");
                return true;
            }
            sender.sendMessage(ChatColor.AQUA+a.name+": "+a.link);
            return true;
        }else {
            List<String> lines = this.getLinks();
            if(lines == null || lines.isEmpty()){
                sender.sendMessage(ChatColor.RED+"There are no links to display.");
                return true;
            }
            int i;
            for(i=0;i<lines.size();i++) {
                sender.sendMessage(ChatColor.AQUA+lines.get(i));
            }
            return true;
        }
    }
}

txtFile.java: txtFile.java:

package com.glostrode.Management.FileIO;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

public class txtFile {
    BufferedReader reader;
    BufferedWriter writer;
    File file;
    int i;
    String path;
    public txtFile(String path) {
        this.path = path;
        this.file = new File(path);
        if(!this.file.exists()){
            try {
                this.file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public boolean getExistence(){
        return this.file.exists();
    }
    public void delete(){
        this.file.delete();
    }
    public void initiateReader(){
        try {
            this.reader = new BufferedReader(new FileReader(this.file));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
    public void initiateWriter(){
        try {
            this.writer = new BufferedWriter(new FileWriter(this.file,true));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public boolean includes(String item){
        if(this.getLines().size()==0){
            return false;
        }else{
            if(this.getLines().contains(item)){
                return true;
            }return false;
        }
    }
    public String getLineWithSubstring(String item){
        List<String> a = this.getLines();
        int i;
        for(i=0;i<a.size();i++){
            if(a.get(i).contains(item)){
                return a.get(i);
            }
        }return "EMPTY_LINE";
    }
    public String getLineAtPos(int pos){
        this.initiateReader();
        int i;
        for(i = 0;i<this.getLines().size();i++){
            if(i == pos){
                return this.getLines().get(i);
            }
        }return null;
    }
    public List<String> getLines(){
        String ln;
        this.initiateReader();
        try {
            List<String> res = new ArrayList<String>();
            for(this.i = 0;(ln = this.reader.readLine()) != null;this.i++){
                res.add(ln.trim());
            }
            this.reader.close();
            return res;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    public void addObject(Object obj){
        try {
            FileOutputStream f = new FileOutputStream(this.file);
            ObjectOutputStream o = new ObjectOutputStream(f);
            o.writeObject(obj);
            o.flush();
            o.close();
            f.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public Object getObject(){
        try {
            FileInputStream i = new FileInputStream(this.file);
            ObjectInputStream o = new ObjectInputStream(i);
            Object r = o.readObject();
            o.close();
            i.close();
            return r;
        } catch (IOException | ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
    public void close() {
        try {
            this.writer.close();
            this.reader.close();
        }catch(IOException e) {
            e.printStackTrace();
        }
    }
    public void replaceLine(int pos, String t){
        List<String> previous = this.getLines();
        previous.set(pos, t);
        this.removeAll("");
        this.addLines(previous);
    }
    public void addLine(String str){
        try {
            this.initiateWriter();
            this.writer.append(str);
            this.writer.newLine();
            this.writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void addLines(List<String> str){
        this.initiateWriter();
        int i;
        for(i=0;i<str.size();i++){
            try {
                this.writer.newLine();
                this.writer.append(str.get(i));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }try {
            this.writer.flush();
            this.writer.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public void removeLine(String str){
        List<String> fileContents = this.getLines();
        this.file.delete();
        int i;
        for(i = 0;i<fileContents.size();i++){
            if(i == fileContents.indexOf(str)){
                fileContents.remove(i);
                i = fileContents.size();
            }
        }
        for(i=0;i<fileContents.size();i++){
            this.addLine(fileContents.get(i));
        }
    }
    public void removeAll(String except){
        this.initiateWriter();
        try {
            this.writer.write(except);
            this.writer.flush();
            this.writer.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
    }
}

Okay, 好的,
The problem is with how you called your addObject method. 问题在于您如何调用addObject方法。
Since you called it with Link.class it returns Class object only. 由于您是使用Link.class调用的,因此它仅返回Class对象。
Which can not be cast to Link on Link li = (Link) o 不能转换为Link li =(Link)o上的Link

Instead just pass Link object. 相反,只需传递Link对象。

addObject(l)

Where l is Link's object 其中l是Link的对象

lf.addObject(l.getClass());

You write a Class object, you get a Class object. 您编写一个Class对象,就得到一个Class对象。

Do this instead: 改为这样做:

lf.addObject(l);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 java.lang.ClassCastException:无法将java.lang.Class强制转换为java.lang.reflect.ParameterizedType - java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType How to fix java.lang.ClassCastException: java.lang.Class cannot be cast to java.util.Map - How to fix java.lang.ClassCastException: java.lang.Class cannot be cast to java.util.Map ClassCastException:java.lang.Class无法强制转换为java.lang.reflect.ParameterizedType - ClassCastException:java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType 引起:java.lang.ClassCastException:使用Generic Type时,libcore.reflect.ParameterizedTypeImpl无法强制转换为java.lang.Class - Caused by: java.lang.ClassCastException: libcore.reflect.ParameterizedTypeImpl cannot be cast to java.lang.Class when use Generic Type “无法转换为java.lang.Class”,即:哪种类型不是类 - “Cannot be cast to java.lang.Class”, namely: which type is not a class class java.lang.Class cannot be cast to class java.lang.reflect.Parameterized - class java.lang.Class cannot be cast to class java.lang.reflect.Parameterized 调用EJB Bean方法时,不能将java.lang.Class强制转换为java.lang.String - java.lang.Class cannot be cast to java.lang.String when invoking a EJB Bean Method java.lang.Class无法强制转换为java.lang.reflect.ParameterizedType - java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType Spring,CXF,java.lang.Class无法转换为[Ljava.lang.Class; - Spring, CXF, java.lang.Class cannot be cast to [Ljava.lang.Class; java.lang.ClassCastException(无法将类转换为同一类) - java.lang.ClassCastException (Cannot cast class to same class)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM