最近在写一个xml测试,临时需要就改成了内部类的方式,结果犯了一个新手经常出现的错误,真不应该
No enclosing instance of type XMLTest is accessible. Must qualify the allocation with an enclosing instance of type XMLTest (e.g. x.new A() where x is an instance of XMLTest).
package com.chinatelecom.web.trade.demo; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.annotation.XmlRootElement; public class XMLTest { @XmlRootElement class Person { private String code; private String name; private int salary; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getSalary() { return salary; } public void setSalary(int population) { this.salary = population; } } public static void main(String[] args) throws JAXBException { JAXBContext context = JAXBContext.newInstance(Person.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); Person person = new Person(); // 此句有问题,解决方法如下 person.setCode("CA"); person.setName("Cath"); person.setSalary(300); m.marshal(person, System.out); } }
而主程序是public static class main。在Java中,类中的静态方法不能直接调用动态方法。只有将某个内部类修饰为静态类,然后才能够在静态类中调用该类的成员变量与成员方法。所以在不做其他变动的情况下,最简单的解决办法是将内部类class改为static静态修饰,问题解决,如果不想改成静态类,那么就new一个主程序变量,然后再new内部类对象吧!
未经允许请勿转载:程序喵 » 【Java异常】No enclosing instance of type XXX is accessible. Must qualify the allocation with