How to add an arrayList to this child class? - java

Context - So there are two classes that uses inheritance. The EmployeeService is the parent class and the EmployeeInfo is the child class.
What do I need help with - So I am trying to insert an arrayList to the parent class that combines the information of the experience and position and makes a new arrayList called serviceList.
And when I call a super() in the child class, I should be able to call the arrayList rather than the String variables (experience, position).
To put it short, I should basically be able to pass an arrayList as the third parameter in the child class employeeInfo method instead of String experience or String position
Parent class -
public class EmployeeService () {
private String experience;
private String position;
public EmployeeService (String experience, String position) {
this.setExperience (experience);
this.setPosition(position);
}
public String getExperience() {
return experience;
}
public void setExperience(String experience) {
this.experience = experience;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
public String toString() {
return "Experience - " + experience + "Position" + " - " + position;
}
}
Child class -
public class EmployeeInfo () {
private String firstName;
private String address;
public EmployeeInfo (String firstName, String address,String experience, String position) {
super(experience, position);
this.setFirstName (firstName);
this.setAddress(address);
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String toString() {
return "Name - " + firstName + "Address" + " - " + address + super.toString();
}
}

Just add the property and an additional constructor to the parent class as follows:
import java.util.ArrayList;
import java.util.List;
public class EmployeeService {
private String experience;
private String position;
private List<String> serviceList;
public EmployeeService (String experience, String position) {
this.setExperience (experience);
this.setPosition(position);
}
public EmployeeService (String experience, String position, List<String> serviceList) {
this(experience, position);
this.serviceList = new ArrayList<>(serviceList);
}
public String getExperience() {
return experience;
}
public void setExperience(String experience) {
this.experience = experience;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
public String toString() {
return "Experience - " + experience + "Position" + " - " + position;
}
}
Then adapt your child class:
import java.util.List;
public class EmployeeInfo extends EmployeeService {
private String firstName;
private String address;
public EmployeeInfo (String firstName, String address, String experience, String position) {
super(experience, position);
this.setFirstName (firstName);
this.setAddress(address);
}
public EmployeeInfo (String firstName, String address, String experience, String position, List<String> serviceList) {
super(experience, position, serviceList);
this.setFirstName (firstName);
this.setAddress(address);
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String toString() {
return "Name - " + firstName + "Address" + " - " + address + super.toString();
}
}

Related

Getting null while Parsing XML

I'm trying to parse strig xml using JaxB API.
Below is my code
XML
http://www.devx.com/supportitems/showSupportItem.php?co=38898&supportitem=listing1
Pojo Classes
#XmlRootElement(name = "employees")
public class FileWrapper {
private LinkedHashSet<Employee> employees;
public LinkedHashSet<Employee> getEmployees() {
return employees;
}
#XmlElement(name = "employee")
public void setEmployees(LinkedHashSet<Employee> employees) {
this.employees = employees;
}
}
Employee.java
import javax.xml.bind.annotation.XmlAttribute;
public class Employee {
private String division;
private String firstname;
private String id;
private String title;
private String building;
private String room;
private String supervisor;
private String lastname;
public String getDivision() {
return division;
}
#XmlAttribute
public void setDivision(String division) {
this.division = division;
}
public String getFirstname() {
return firstname;
}
#XmlAttribute
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getId() {
return id;
}
#XmlAttribute
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
#XmlAttribute
public void setTitle(String title) {
this.title = title;
}
public String getBuilding() {
return building;
}
#XmlAttribute
public void setBuilding(String building) {
this.building = building;
}
public String getRoom() {
return room;
}
#XmlAttribute
public void setRoom(String room) {
this.room = room;
}
public String getSupervisor() {
return supervisor;
}
#XmlAttribute
public void setSupervisor(String supervisor) {
this.supervisor = supervisor;
}
public String getLastname() {
return lastname;
}
#XmlAttribute
public void setLastname(String lastname) {
this.lastname = lastname;
}
#Override
public String toString() {
return "ClassPojo [division = " + division + ", firstname = " + firstname + ", id = " + id + ", title = "
+ title + ", building = " + building + ", room = " + room + ", supervisor = " + supervisor
+ ", lastname = " + lastname + "]";
}
}
MainEntry
public class TestEntryPoint {
public static void main(String[] args) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(FileWrapper.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
StringReader reader = new StringReader("XML from above link as String");
FileWrapper person = (FileWrapper) unmarshaller.unmarshal(reader);
List<Employee> emp = new ArrayList<Employee>(person.getEmployees());
System.out.println(emp.get(0).getFirstname());
}
}
So when am trying to extract any tag's value its showing null. Is there any problem with my XML's data structure or pojo classes ? I'm stuck in this from last couple of hours.
What am doing wrong ? Canyone suggest please ?
Thanks
Annotations in Employee class refer to XML attributes instead of the elements.
Here is corrected version:
public class Employee {
private String division;
private String firstname;
private String id;
private String title;
private String building;
private String room;
private String supervisor;
private String lastname;
public String getDivision() {
return division;
}
#XmlElement(name = "division")
public void setDivision(String division) {
this.division = division;
}
public String getFirstname() {
return firstname;
}
#XmlElement(name = "firstname")
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getId() {
return id;
}
#XmlAttribute
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
#XmlElement(name = "title")
public void setTitle(String title) {
this.title = title;
}
public String getBuilding() {
return building;
}
#XmlElement(name = "building")
public void setBuilding(String building) {
this.building = building;
}
public String getRoom() {
return room;
}
#XmlElement(name = "room")
public void setRoom(String room) {
this.room = room;
}
public String getSupervisor() {
return supervisor;
}
#XmlElement(name = "supervisor")
public void setSupervisor(String supervisor) {
this.supervisor = supervisor;
}
public String getLastname() {
return lastname;
}
#XmlElement(name = "lastname")
public void setLastname(String lastname) {
this.lastname = lastname;
}
#Override
public String toString() {
return "ClassPojo [division = " + division + ", firstname = " + firstname + ", id = " + id + ", title = "
+ title + ", building = " + building + ", room = " + room + ", supervisor = " + supervisor
+ ", lastname = " + lastname + "]";
}
}

How to extract the methods of the a nested object using reflection

How do I access the getter methods of a nested custom object? I am able to extract the methods which return Strings but not able to extract methods of a nested object.
My implementation is as follows:
public class DataExtraction {
public void showTheData(Object student) throws IOException {
Class classofStudent = student.getClass();
Method[] methodsOfStudent = classofStudent.getDeclaredMethods();
for(Method method:methodsOfStudent)
{
if(isGetType(method))
{
if(method.getReturnType()==String.class)
{
try(InputStream is = new FileInputStream("ObjectFileReaderPrimitive.properties"))
{
//InputStream is = new FileInputStream("ObjectFileReaderPrimitive.properties");
Properties properties = new Properties();
properties.load(is);
System.out.println(properties.getProperty(method.getName()));
}
}
else
try(InputStream is = new FileInputStream("ObjectFileReaderNonPrimitive.properties"))
{
Class innerObjectClass = method.getReturnType().getClass();
Method[] methodsOfinnerObject = innerObjectClass.getDeclaredMethods();
for(Method methodofInnerClass : methodsOfinnerObject) {
if(isGetType(method))
{
Properties properties = new Properties();
properties.load(is);
System.out.println(properties.getProperty(methodofInnerClass.getName()));
}
}}
}
}}
private boolean isGetType(Method method) {
if(method.getName().startsWith("get"))
return true;
return false;
}
}
Where the student class is as follows-:
package com.sample;
public class Student {
private String id;
private String section;
private Address address;
public Student(String id, String section, Address address) {
super();
this.id = id;
this.section = section;
this.address = address;
}
public Student() {
super();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSection() {
return section;
}
public void setSection(String section) {
this.section = section;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
#Override
public String toString() {
return "Student [id=" + id + ", section=" + section + ", address=" + address + "]";
}
}
Address Object-:
package com.sample;
public class Address {
private String AddressLine1;
private String AddressLine2;
private String AddressLine3;
public Address(String addressLine1, String addressLine2, String addressLine3) {
super();
AddressLine1 = addressLine1;
AddressLine2 = addressLine2;
AddressLine3 = addressLine3;
}
public Address() {
super();
}
public String getAddressLine1() {
return AddressLine1;
}
public void setAddressLine1(String addressLine1) {
AddressLine1 = addressLine1;
}
public String getAddressLine2() {
return AddressLine2;
}
public void setAddressLine2(String addressLine2) {
AddressLine2 = addressLine2;
}
public String getAddressLine3() {
return AddressLine3;
}
public void setAddressLine3(String addressLine3) {
AddressLine3 = addressLine3;
}
#Override
public String toString() {
return "Address [AddressLine1=" + AddressLine1 + ", AddressLine2=" + AddressLine2 + ", AddressLine3="
+ AddressLine3 + "]";
}
}
Your problem is that you are not actually getting the correct class for your inner custom object.
Currently you are doing:
Class innerObjectClass = method.getReturnType().getClass();
This does not work because the method getReturnType is already returning the Class object of the return type. So what is happening is you are calling getClass() on a class object. This will return class java.lang.Class. You just need to remove the call to getClass:
Class innerObjectClass = method.getReturnType();
Here I have modified your code so that it prints all the getter objects in Student and Address
Class classofStudent = Student.class;
Method[] methodsOfStudent = classofStudent.getDeclaredMethods();
for (Method method : methodsOfStudent) {
if (isGetType(method)) {
if (method.getReturnType() == String.class) {
System.out.println(method.getName());
} else {
Class innerObjectClass = method.getReturnType();
Method[] methodsOfinnerObject = innerObjectClass.getDeclaredMethods();
for (Method methodofInnerClass : methodsOfinnerObject) {
if (isGetType(method)) {
System.out.println(methodofInnerClass.getName());
}
}
}
}
}

How to add a mongo id from one collection as a foreign key in another collection

In my Spring boot application, I have collection of Todos and a collection of Courses. In the view of the application, I return the collection of courses and display whatever course I need. The Todos are stored as 1 list which represents all the current Todos. What I would like to do is return a list of Todos for each course. So when the view is opened, the application would display the the course plus the individual todo list for that course.
Is there a way I can use the existing code to incorporate the new functionality. I have created the front end logic and would like to keep that. My initial idea was to add the the course id to the Todo.java, but that did not work.
Todo.java
#Document(collection="todos")
public class Todo {
#Id
private String id;
#NotBlank
#Size(max=250)
#Indexed(unique=true)
private String title;
private Boolean completed = false;
private Date createdAt = new Date();
public Todo() {
super();
}
public Todo(String title) {
this.title = title;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Boolean getCompleted() {
return completed;
}
public void setCompleted(Boolean completed) {
this.completed = completed;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
#Override
public String toString() {
return String.format(
"Todo[id=%s, title='%s', completed='%s']",
id, title, completed);
}
}
TodoRepository.java
#Repository
public interface TodoRepository extends MongoRepository<Todo, String> {
public List<Todo> findAll();
public Todo findOne(String id);
public Todo save(Todo todo);
public void delete(Todo todo);
}
Courses
#Document(collection = "courses")
public class Courses {
#Id
private String id;
private String name;
private String lecturer;
private String picture;
private String video;
private String description;
private String enroled;
public Courses(){}
public Courses(String name, String lecturer, String picture, String video, String description,String enroled) {
this.name = name;
this.lecturer = lecturer;
this.picture = picture;
this.video = video;
this.description = description;
this.enroled = enroled;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLecturer() {
return lecturer;
}
public void setLecturer(String lecturer) {
this.lecturer = lecturer;
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
public String getVideo() {
return video;
}
public void setVideo(String video) {
this.video = video;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getEnroled() {
return enroled;
}
public void setEnroled(String enroled) {
this.enroled = enroled;
}
#Override
public String toString() {
return "Courses{" +
"id='" + id + "'" +
", name='" + name + "'" +
", lecturer='" + lecturer + "'" +
", description='" + description + "'" +
'}';
}
}

Work with methods, setters and getters in java

I have this class:
public class Person
{
/**
*
*/
private static final long serialVersionUID = 1L;
private String firstName = "Vasya";
private String lastName = "Pupkin";
private Integer age = 58;
private Integer phone = 2;
#Override
public String toString()
{
return "Person [firstName=" + firstName + ", lastName=" + lastName
+ ", age=" + age + "]";
}
public void setName(String name)
{
firstName = name;
}
public void setLastName(String lName)
{
lastName = lName;
}
public void setAge(Integer personAge)
{
age = personAge;
}
public void setPhone(Integer personPhone)
{
phone = personPhone;
}
public String getName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public Integer getAge()
{
return age;
}
public Integer getPhone()
{
return phone;
}
public void Init()
{
this.setName("");
this.setLastName("");
this.setPhone(0);
this.setAge(0);
}
}
I create an variable: Person somePerson, then I call method setName from that variable somePerson:
somePerson.setName("");
but it raises an error.
Based on the provided code, the following should work:
Person somePerson = new Person();
somePerson.setName("");
If it doesn't, then something else is going on.

sorting an arrayList<class> by its integer contents

I am passing an arrayList to a method to sort its data.
The data in the arrayList would contain multiple id numbers correlating to different students.
the array will also include other information. How do i sort the arrayList by its id #. I believe it will have to do with my created class which is included below
more code can be provided as necessary
public static class Student {
public String firstName;
public String lastName;
public Integer uid;
public StudentType type;
public Student(Student orig) {
this.firstName = orig.firstName;
this.lastName = orig.lastName;
this.uid = orig.uid;
this.type = orig.type;
}
// construct a new student with given fields
public Student(String firstName, String lastName, Integer newUid, StudentType type) {
this.firstName = firstName;
this.lastName = lastName;
this.uid = newUid;
this.type = type;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
//set type
public void setType(StudentType type) {
this.type = type;
}
//return type
public StudentType getType() {
return type;
}
public void setUid(Integer uid){
this.uid = uid;
}
public Integer getUid() {
return uid;
}
// return a string representation of the invoking object
public String toString() {
return firstName + " " + lastName + " " + uid + " " + type;
}
public static class Graduate extends Student {
public boolean thesis;
public ClassStanding study;
public String profName;
public Graduate(Student orig, boolean isThesis, ClassStanding study, String profName) {
super(orig);
thesis = isThesis;
this.study = study;
this.profName = profName;
}
public boolean getThesis() {
return thesis;
}
public void setThesis(Boolean thesis) {
this.thesis = thesis;
}
public ClassStanding getStudy() {
return study;
}
public void setStudy(ClassStanding study) {
this.study = study;
}
public String getProfName() {
return profName;
}
public void setProfName(String profName) {
this.profName = profName;
}
public String toString() {
return super.toString() + thesis + " " + study + " " + profName;
}
}
public static class UnderGraduate extends Student {
public Major major;
public Double overallGpa;
public Double majorGpa;
public ClassStanding study;
public UnderGraduate(Student orig, Major major, Double overallGpa, Double majorGpa, ClassStanding study) {
super(orig);
this.study = study;
this.major = major;
this.overallGpa = overallGpa;
this.majorGpa = majorGpa;
}
public void setMajor(Major major) {
this.major = major;
}
//return type
public Major getmMajor() {
return major;
}
public void setOverallGPA(Double overallGpa) {
this.overallGpa = overallGpa;
}
public Double getOverallGPA() {
return overallGpa;
}
public void setMajorGPA(Double majorGpa) {
this.majorGpa = majorGpa;
}
public Double getMajorGPA() {
return majorGpa;
}
public ClassStanding getStudy() {
return study;
}
public void setStudy(ClassStanding study) {
this.study = study;
}
public String toString() {
return study + " " + major + " " + overallGpa + " " + majorGpa;
}
}
}
Collections.sort(myListofStudents, new Comparator<Student>() {
#Override
public int compareTo(Student s1, Student s2) {
return s1.getUid().compareTo(s2.getUid());
}
});
Alternatively, you can have Student implement Comparable<Student>, which means including a .compareTo().
NB: If you're going to override .compareTo(), you should override .equals(), which means you should override hashCode().
Define a Comparator<Student> and use it with Collections.sort:
public class StudentComparator implements Comparator<Student> {
#Override
public int compare (Student s1, Student s2) {
// Your comparison logic here
}
}
...then...
Collections.sort(data, new StudentComparator());
See the JavaDoc on Comparator for more information.
Create a Comparator for Student, then use Collections.sort()

Categories