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

时间:2018-07-03 19:30:02

标签: java classcastexception

所以我得到了

  

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

以下方法指示的行(文件的第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;
}

getLines()方法返回一个List<String>,其中包含在txtFile对象的初始化中指定的文件中的行。 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;
    }
}

根据我目前的理解,由o.readObject()返回的对象应可转换为其原始形式(读取的文件包含Link对象)。

我使用以下方法将其添加到文件中:

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构造函数:

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();
            }
        }
    }
}

源代码: 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:

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();
        } 
    }
}

2 个答案:

答案 0 :(得分:4)

好的,
问题在于您如何调用 addObject 方法。
由于您是使用Link.class调用的,因此它仅返回 Class 对象。
无法将其强制转换为Link li =(Link)o

上的Link

相反,只需传递Link对象。

addObject(l)

其中l是Link的对象

答案 1 :(得分:0)

lf.addObject(l.getClass());

您编写了一个Class对象,您得到了一个Class对象。

执行此操作:

lf.addObject(l);
相关问题