class java.util.ArrayList nor any of its super class is known to this context
У меня есть задача по загрузке класса репозитория в XML файл.
Код класса Repository: package com.mycompany.laba1;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import org.joda.time.DateTime;
import org.joda.time.Period;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.*;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.*;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.Month;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
import java.util.function.Predicate;
import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Class Repository is intended for store objects class IPerson.
*
*
* @author Data
*/
@XmlRootElement
public class Repository implements IRepository {
/**
* Field size store size massiv.
*/
private int size;
@XmlElement(type = Object.class)
private IPerson[] mass;
private int count = 0;
/**
* This is constructor. In constructor we initialize property size and array
* mass of type IPerson
*
*
* @author Data
* @param size
*/
public Repository(int size) {
this.size = size;
mass = new IPerson[size];
}
/**
* Method setSize set size.
*
* @param size
*/
public final void setSize(int size) {
this.size = size;
}
/**
* Method getSize return size.
*
* @return
*/
public final int getSize() {
return size;
}
/**
* Method add -add Object into array mass.
*
*/
public void add(IPerson person) {
/* if (count == size)
{
int currentCapacity = mass.length;
IPerson[] tempArr = new IPerson[currentCapacity + currentCapacity];
for(int i = 0; i < mass.length; i++) {
tempArr[i] = mass[i];
}
mass = tempArr;
}*/
int firstLength = mass.length;
for (int i = 0; i < mass.length; i++) {
if (mass[i] != null && i == mass.length - 1) {
int currentCapacity = mass.length;
IPerson[] tempArr = new IPerson[currentCapacity * 2];
for (int j = 0; j < currentCapacity; j++) {
tempArr[j] = mass[j];
}
// mass = new IPerson[tempArr.length];
mass = tempArr;
// mass[currentCapacity]=obj;
// break;
}
if (mass[i] == null) {
mass[i] = person;
break;
}
}
//else
}
/**
* Method add -add Object into array mass, if element mass[index] is null.
*
*/
public void add(int index, IPerson person) {
if (mass[index] == null) {
mass[index] = person;
} else //throw new Exception("This index contains element");
{
Optional.of("This index contains element");
}
}
/**
* Method set -replace element array "mas" with "index" for object "person".
*
* @param index
* @param person
*/
public IPerson set(int index, IPerson person) {
mass[index] = person;
return person;
}
/**
* Method get -return element array "mass" for given "index".
*
*/
public IPerson get(int index) {
return mass[index];
}
/**
* Method toList -convert array "mass" to Collection "List".
*
*/
public List<IPerson> toList() {
ArrayList<IPerson> arr = new ArrayList<>();
for (int i = 0; i < mass.length; i++) {
if (mass[i] != null) {
arr.add(mass[i]);
}
}
return arr;
}
/**
* Method delete(int index) receive index element massiv and delete this
* element.
*
* @param index
*/
public IPerson delete(int index) {
/* int size2 = mass.length - 1;
IPerson[] mass2 = new IPerson[size2];
System.arraycopy(mass, 0, mass2, 0, index);
System.arraycopy(mass, index + 1, mass2, index,
mass.length - index - 1);
// count--;
mass = new IPerson[size2];
System.arraycopy(mass2, 0, mass, 0, size2);
mass[index+1]=null;*/
/* for (int i = index; i < mass.length-1; i++)
{
mass[i] = mass[i + 1];
}
int[] newArr = new int[mass.length - 1];
System.arraycopy(mass, 0, newArr, 0, mass.length - 1);*/
// return mass[index];
int count2 =mass.length-1;
IPerson oldValue = mass[index];
int numMoved = count2 - index - 1;
if (numMoved > 0) {
System.arraycopy(mass, index+1, mass, index, numMoved);
}
mass[--count2] = null;
return oldValue;
}
/**
* Method getMass - return array "mass"
*
*/
public IPerson[] getMass() {
int countNotNullElement = 0;
for (int i = 0; i < mass.length; i++) {
if (mass[i] != null) {
countNotNullElement++;
}
}
int currentIndex = 0;
IPerson[] mass2 = new IPerson[countNotNullElement];
for (int i = 0; i < mass.length; i++) {
if (mass[i] != null) {
mass2[currentIndex++] = mass[i];
}
}
// mass=mass2;
return mass2;
}
/**
* Method readFromFileInRepository - read file and add to array "mass" with
* method add(IPerson obj)
*
* @param fileName
*/
/**
* Method SortBy-sort array "mass" with given comparator
*
* @param comparator
*/
public void sortBy(Comparator<IPerson> comparator) {
BubbleSorter bs=new BubbleSorter();
bs.sortby(comparator, mass);
/* try {
bs.bubbleSort(comparator);
} catch (InstantiationException ex) {
Logger.getLogger(Repository.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchFieldException ex) {
Logger.getLogger(Repository.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(Repository.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(Repository.class.getName()).log(Level.SEVERE, null, ex);
}*/
InsertionSorter is=new InsertionSorter();
is.sortby(comparator, mass);
}
public IRepository searchBy(Predicate<IPerson> condition) {
IRepository buf = new Repository(size);
IDivision div = new Division("A");
IDivision div2 = new Division("B");
IDivision div3 = new Division("C");
// System.out.println("Hello World");
LocalDate localDate1 = LocalDate.of(1960, Month.MAY, 14);
LocalDate localDate2 = LocalDate.of(1965, Month.MAY, 14);
LocalDate localDate3 = LocalDate.of(1970, Month.MAY, 14);
BigDecimal bd = new BigDecimal(20000);
BigDecimal bd2 = new BigDecimal(25000);
BigDecimal bd3 = new BigDecimal(35000);
IPerson p1 = new Person(1, "Valeriy", "Petrov",Gender.MALE, localDate1, div, bd);
IPerson p2 = new Person(5, "Valeriy", "Petrov",Gender.MALE, localDate1, div, bd);
IPerson p3 = new Person(6, "Valeriy", "Petrov",Gender.MALE, localDate1, div2, bd);
IPerson p4 = new Person(7, "Valeriy", "Petrov", Gender.MALE,localDate2, div, bd);
IPerson p5 = new Person(8, "Valeriy", "Petrov", Gender.MALE,localDate1, div, bd);
IPerson p6 = new Person(9, "Vera", "Petrova",Gender.FEMALE, localDate1, div3, bd2);
IPerson p7 = new Person(10, "Ivan", "Ivanov", Gender.MALE,localDate3, div, bd);
IPerson p8 = new Person(0, "Vladimir", "Smirnov",Gender.MALE, localDate1, div, bd3);
buf.add(p1);
buf.add(p2);
buf.add(p3);
buf.add(p4);
for (int i = 0; i < buf.toList().size(); i++) {
if (condition.test(mass[i])) {
return buf;
}
}
return buf;
}
}
Поскольку класс содержит массив обектов интерфейса IPerson(данный интерфейс имплементит класс Person), а библиотека JAXB не работает с интерфейсами, я создал промежуточный класс PersonForXML, чтобы туда переписать данные без интерфейсов. Код класса Person:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.laba1;
import java.math.BigDecimal;
import org.joda.time.DateTime;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import org.joda.time.Period;
/**
* Class Person contains four field: 1) id as identifikator; 2) Name-Name Father
* Surname; 3) date - date birthday 4) sex - sex Person
*
* Methods getDate(),getSex(),getId(), getName() -returns values fields class
* Methods setDate(),setSex(),setId(), setName() -set values fields class
*
* Method difference_date() -calcute age Person
*
* @author Data
*/
public class Person implements IPerson {
/**
* Filed "id" as identifikator.
*
*/
private int id;
/**
* Filed "Name"-Name Father Surname.
*
*/
private String FirstName;
private String LastName;
private LocalDate Birthdate;
/**
* Filed date - date birthday.
*
*/
/**
* Filed Gender - sex Person.
*
*/
private Gender Gender;
/**
* Filed Salary - Salary for Person.
*
*/
private BigDecimal Salary;
public IDivision IDivision;
/**
* Method getId() return Id.
*
* @return
*/
public Integer getId() {
return id;
}
/**
* Method setId set field Id.
*
* @param id
*/
public final void setId(Integer id) {
this.id = id;
}
/**
* Method getFirstName return filedt FirstName.
*
*/
public String getFirstName() {
return FirstName;
}
/**
* Method getFirstName set filed FirstName.
*
* @param FirstName
*/
public String setFirstName(String FirstName) {
this.FirstName = FirstName;
return this.FirstName;
}
/**
* Method getlastName return filed LastName.
*
*/
public String getLastName() {
return LastName;
}
/**
* Method setLastName set filed LastName.
*
* @param FirstName
*/
public String setLastName(String LastName) {
this.LastName = LastName;
return this.LastName;
}
/**
* Method getBirthdate return filed Birthdate.
*
*/
public LocalDate getBirthdate() {
return Birthdate;
}
/**
* Method setBirthdate set filed Birthdate.
*
* @param Birthdate
*/
public LocalDate setBirthdate(LocalDate Birthdate) {
this.Birthdate = Birthdate;
return this.Birthdate;
}
/**
* Method getSalary return filed Salary.
*
*/
public BigDecimal getSalary() {
return Salary;
}
/**
* Method setSalary set filed Salary.
*
* @param Salary
*/
public void setSalary(BigDecimal Salary) {
this.Salary = Salary;
}
/**
* Method getGender return gender Person.
*
*/
public Gender getGender() {
return Gender;
}
/**
* Method setGender set gender Person.
*
* @param Gender
*/
public void setGender(Gender Gender) {
this.Gender = Gender;
}
/**
* Method getDivision return gender Person.
*
*/
public IDivision getDivision() {
return IDivision;
}
/**
* Method getDivision return field setDivision.
*
* @param division
*/
public void setDivision(IDivision division) {
this.IDivision = IDivision;
}
/**
* This is constructor.
*
* @param id
* @param FirstName
* @param Name
* @param Birthdate
* @param Gender
* @param Salary
*
*/
public Person(int id, String FirstName, String LastName, Gender Gender,LocalDate Birthdate, String Name, BigDecimal Salary) {
this.id = id;
this.FirstName = FirstName;
this.LastName = LastName;
this.Gender = Gender;
this.Birthdate = Birthdate;
this.IDivision.setName(Name);
this.Salary = Salary;
}
public Person(int id, String FirstName, String LastName,Gender Gender, LocalDate Birthdate, IDivision IDivision, BigDecimal Salary ) {
this.id = id;
this.FirstName = FirstName;
this.LastName = LastName;
this.Gender = Gender;
this.Birthdate = Birthdate;
this.IDivision = IDivision;
this.Salary = Salary;
}
/**
* Method getAge calculate and print age Person.
*/
public Integer getAge() {
LocalDate now = LocalDate.now();
//Period p = new Period(date, now);
int years = (int) ChronoUnit.YEARS.between(Birthdate, now);
return years;
}
}
Код интерфейса IPerson:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.laba1;
import java.math.BigDecimal;
import java.time.LocalDate;
/**
*
* @author Data
*/
public interface IPerson {
public Integer getId();
public void setId(Integer id);
public String getFirstName();
public String setFirstName(String firstName);
public String getLastName();
public String setLastName(String firstName);
public LocalDate getBirthdate();
public LocalDate setBirthdate(LocalDate birthdate);
public Integer getAge();
public Gender getGender();
public void setGender(Gender gender);
public IDivision getDivision();
public void setDivision(IDivision division);
public BigDecimal getSalary();
public void setSalary(BigDecimal salary);
}
Код класса PersonForXML:
package com.mycompany.laba1;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import java.math.BigDecimal;
import java.time.LocalDate;
@XmlAccessorType(XmlAccessType.FIELD)
public class PersonForXML {
private Integer Id;
private String FirstName;
private String LastName;
private LocalDate Birthdate;
private Integer Age;
private Gender Gender;
private String Name;
private BigDecimal Salary;
public BigDecimal getSalary() {
return Salary;
}
public void setSalary(BigDecimal salary) {
Salary = salary;
}
public Integer getId() {
return Id;
}
public void setId(Integer id) {
Id = id;
}
public String getFirstName() {
return FirstName;
}
public void setFirstName(String firstName) {
FirstName = firstName;
}
public String getLastName() {
return LastName;
}
public void setLastName(String lastName) {
LastName = lastName;
}
public LocalDate getBirthdate() {
return Birthdate;
}
public void setBirthdate(LocalDate birthdate) {
Birthdate = birthdate;
}
public Integer getAge() {
return Age;
}
public void setAge(Integer age) {
Age = age;
}
public com.mycompany.laba1.Gender getGender() {
return Gender;
}
public void setGender(com.mycompany.laba1.Gender gender) {
Gender = gender;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public PersonForXML(Integer id, String firstName, String lastName, LocalDate birthdate, Integer age, com.mycompany.laba1.Gender gender, String name, BigDecimal salary) {
Id = id;
FirstName = firstName;
LastName = lastName;
Birthdate = birthdate;
Age = age;
Gender = gender;
Name = name;
Salary = salary;
}
}
Код класса WriteReadXML(который осуществляет загрузку класса Repository в XML файл):
package com.mycompany.laba1;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.*;
import java.io.File;
import java.util.ArrayList;
@XmlSeeAlso(ArrayList.class)
@XmlRootElement(name = "personForXML")
@XmlAccessorType(XmlAccessType.FIELD)
public class WriteReadXML {
public void writeXMLinFile(/*ArrayList<IPerson> persons,*/ Repository rep,IPerson[] mass) throws JAXBException {
ArrayList<PersonForXML> personsForXML=new ArrayList<>();
for(int i=0;i<rep.getMass().length;i++)
{
PersonForXML objpersonsForXML=new PersonForXML(rep.getMass()[i].getId(),
rep.getMass()[i].getFirstName(),
rep.getMass()[i].getLastName(),
rep.getMass()[i].getBirthdate(),
rep.getMass()[i].getAge(),
rep.getMass()[i].getGender(),
rep.getMass()[i].getDivision().getName(),
rep.getMass()[i].getSalary()
);
personsForXML.add(objpersonsForXML);
}
JAXBContext jaxbContext = JAXBContext.newInstance(PersonForXML.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
//Marshal the employees list in console
jaxbMarshaller.marshal(personsForXML, System.out);
//Marshal the employees list in file
jaxbMarshaller.marshal(personsForXML, new File("C:\\Users\\Data\\Documents\\NetBeansProjects\\Laba1\\target\\classes\\persons.xml"));
/* File file = new File("C:\\file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Repository.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(rep, file);
jaxbMarshaller.marshal(rep, System.out);*/
}
}
Но когда я в методе main пытаюсь осуществить загрузку репозитория в xml, следующим образом:
Repository c2 = new Repository(1000);
LoadRepository lp = new LoadRepository();
lp.readFromFileInRepository("C:\\Users\\Data\\Documents\\NetBeansProjects\\Laba1\\target\\classes\\persons.csv");
ArrayList<IPerson> listPerson=new ArrayList<>();
listPerson.addAll(lp.getR().toList());
WriteReadXML wrx=new WriteReadXML();
ArrayList<Person> listPerson2=new ArrayList<>();
// listPerson2.addAll((Person)listPerson);
wrx.writeXMLinFile(lp.getR(),lp.getR().getMass());
Я получаю следующие исключения: Exception in thread "main" javax.xml.bind.JAXBException: class java.util.ArrayList nor any of its super class is known to this context. at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.getBeanInfo(JAXBContextImpl.java:567) at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.childAsRoot(XMLSerializer.java:467) at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:308) at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.marshal(MarshallerImpl.java:236) at javax.xml.bind.helpers.AbstractMarshallerImpl.marshal(AbstractMarshallerImpl.java:95) at com.mycompany.laba1.WriteReadXML.writeXMLinFile(WriteReadXML.java:43) at com.mycompany.laba1.Main.main(Main.java:144) Помогите, пожалуйста, разобраться с данной проблемой.