关于Java SE出现报错Exception in thread "main" java.lang.Error: Unresolved compilation problems...

来源:互联网 发布:windows 98系统下载 编辑:程序博客网 时间:2024/05/18 11:45

自学Java一个月了,今天在学习序列化得时候自己动手写了一个例程,如下:

package com.JoyWork.Seria;
import java.io.*;
public class text01 implements Serializable{

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        
    GameCharater Elt = new GameCharater(50,"Elf",new String[]{ "bow","sword","dust"});
    GameCharater Troll = new GameCharater(200,"Troll",new String[]{"bara hands","big ax"});
    

        try{
            FileOutputStream fs = new FileOutputStream("GameCharater.ser");
            ObjectOutputStream os = new ObjectOutputStream(fs);
            os.writeObject(Elt);
            os.writeObject(Troll);
            os.close();
            
        } catch(Exception e){e.printStackTrace();}
        
        
        try{
        
            ObjectInputStream os = new ObjectInputStream(new FileInputStream("GameCharater.ser"));
            Object Elf = os.readObject();
            Object Trolll = os.readObject();
            
            GameCharater elf = (GameCharater)Elf;
            GameCharater  troll = (GameCharater)Trolll;
            
            System.out.println(elf.getPower()+" "+elf.getType());
            System.out.println(troll.getPower()+" "+troll.getType());
            
        }  catch(Exception e){e.printStackTrace();}
        

    }
    
    
    public   class GameCharater implements Serializable{

    private int Power;
    private String Type;
    private String[] weapons;
    
    public GameCharater (int p,String t,String[] w){
        Power = p;
        Type = t;
        weapons = w;
    }
    
    
    
    public int getPower() {
        return Power;
    }



    public String getType() {
        return Type;
    }



    public String getWeapons() {
        String List = null;
        
        for(int i =0;i<weapons.length;i++){
            List     += weapons[i]+" ";
        }
        
        return  List;
    }

    }

}
   

结果发现报错:

Exception in thread "main" java.lang.Error: Unresolved compilation problems:
    No enclosing instance of type text01 is accessible. Must qualify the allocation with an enclosing instance of type text01 (e.g. x.new A() where x is an instance of text01).
    No enclosing instance of type text01 is accessible. Must qualify the allocation with an enclosing instance of type text01 (e.g. x.new A() where x is an instance of text01).

    at com.JoyWork.Seria.text01.main(text01.java:8)

类型text01没有外围实例访问。必须与类型text01类实例限定分配(例如x.newA(,其中x是text01的一个实例)
类型text01没有外围实例访问。必须与类型text01类实例限定分配(例如x.newA(,其中x是text01的一个实例)

经过查阅资料发现是内部类的问题,因为我写的内部类GameCharater是动态的,也就是开头以public class开头。而主程序是public static class main。在Java中,类中的静态方法不能直接调用动态方法。只有将某个内部类修饰为静态类,然后才能够在静态类中调用该类的成员变量与成员方法。

解决办法有两个:1、不要写内部类,写成单独的一个bean对象 2、将内部类写成public static类型的

记录一下,也方便大家参考
0 0
原创粉丝点击