Using reflection to set an object property - java

I getting class by name and i need to update them with respective data and my question is how to do it with java
I want to add the method some dummy data .
I don't know the class type I just getting the class name and use reflection to get his data
I use this code to get the class instance and
Class<?> classHandle = Class.forName(className);
Object myObject = classHandle.newInstance();
// iterate through all the methods declared by the class
for (Method method : classHandle.getMethods()) {
// find all the set methods
if (method.getName().matches("set[A-Z].*")
And know that I find the list of the set method I want to update it with data
how can I do that .
assume that In class name I got person and the class have setSalary and setFirstName etc
how can I set them with reflection ?
public class Person {
public void setSalery(double salery) {
this.salery = salery;
}
public void setFirstName(String FirstName) {
this.FirstName = FirstName;
}
}

Instead of trying to call a setter, you could also just directly set the value to the property using reflection. For example:
public static boolean set(Object object, String fieldName, Object fieldValue) {
Class<?> clazz = object.getClass();
while (clazz != null) {
try {
Field field = clazz.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(object, fieldValue);
return true;
} catch (NoSuchFieldException e) {
clazz = clazz.getSuperclass();
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
return false;
}
Call:
Class<?> clazz = Class.forName(className);
Object instance = clazz.newInstance();
set(instance, "salary", 15);
set(instance, "firstname", "John");
FYI, here is the equivalent generic getter:
#SuppressWarnings("unchecked")
public static <V> V get(Object object, String fieldName) {
Class<?> clazz = object.getClass();
while (clazz != null) {
try {
Field field = clazz.getDeclaredField(fieldName);
field.setAccessible(true);
return (V) field.get(object);
} catch (NoSuchFieldException e) {
clazz = clazz.getSuperclass();
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
return null;
}
Call:
Class<?> clazz = Class.forName(className);
Object instance = clazz.newInstance();
int salary = get(instance, "salary");
String firstname = get(instance, "firstname");

To update the first name
First find the field you want to update
Then find the mutator (which accepts an argument of the field's type)
Finally execute the mutator on the object with the new value:
Field field=classHandle.getDeclaredField("firstName");
Method setter=classHandle.getMethod("setFirstName", field.getType());
setter.invoke(myObject, "new value for first name");

if (method.getName().matches("set[A-Z].*") {
method.invoke(person,salary)
// and so on
}
to know the parameters you can issue method.getPagetParameterTypes()
based on the result construct your parameters and supply.

package apple;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.Map.Entry;
import java.util.Set;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
/*
* Employe Details class
*/
class Employee {
private long id;
private String name;
private String userName;
private Address address;
private Contact contact;
private double salary;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public Contact getContact() {
return contact;
}
public void setContact(Contact contact) {
this.contact = contact;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
/*
* Address class for employee
*/
class Address {
private String city;
private String state;
private String country;
private int pincode;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public int getPincode() {
return pincode;
}
public void setPincode(int pincode) {
this.pincode = pincode;
}
}
/*
* Contact class for Employee
*/
class Contact {
private String email;
private String contactNo;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getContactNo() {
return contactNo;
}
public void setContactNo(String contactNo) {
this.contactNo = contactNo;
}
}
public class Server {
public static void main(String args[]) throws JsonSyntaxException, Exception{
Gson gson = new Gson();
/*
* Old Employee Data
*/
Address address = new Address();
Contact contact = new Contact();
Employee employee = new Employee();
address.setCity("shohna-road");
address.setCountry("INDIA");
address.setPincode(12201);
address.setState("Hariyana");
contact.setContactNo("+918010327919");
contact.setEmail("shivritesh9984#gmail.com");
employee.setAddress(address);
employee.setContact(contact);
employee.setId(4389573);
employee.setName("RITESH SINGH");
employee.setSalary(43578349.345);
employee.setUserName("ritesh9984");
System.out.println("Employee : "+gson.toJson(employee));
/* New employee data */
Employee emp = employee;
address.setCity("OMAX");
emp.setAddress(address);
emp.setName("RAVAN");
/* Update employee with new employee Object*/
update(employee, gson.fromJson(gson.toJson(emp), JsonObject.class) );
System.out.println("Employee-Update : "+gson.toJson(employee));
}
/*
* This method update the #target with new given value of new object in json object form
*/
public static void update(Object target, JsonObject json) throws Exception {
Gson gson=new Gson();
Class<? > class1 = target.getClass();
Set<Entry<String, JsonElement>> entrySet = json.entrySet();
for (Entry<String, JsonElement> entry : entrySet) {
String key = entry.getKey();
Field field = class1.getDeclaredField(key);
field.setAccessible(true);
Type genType = field.getGenericType();
field.set(target,
gson.fromJson(entry.getValue(),genType));
}
}
}

Related

JsonMappingException: N/A when trying to deserialize JSON file

I have a User class and a Json file containing an array of Users. When trying to deserialize those users and get a List I'm getting a JsonMappingException, I don't understand what's wrong.
This is my User class:
public class User {
private StringProperty username;
private StringProperty password;
private StringProperty name;
private StringProperty surname;
private StringProperty email;
private StringProperty company;
private StringProperty phone;
private BooleanProperty canMonitorize;
private BooleanProperty canCreateProject;
private BooleanProperty canOpenProject;
private BooleanProperty admin;
public User() {}
public User(String user, String pass, String name, String surname, String email, String company, String phone,
boolean monitorize, boolean createP, boolean openP, boolean admin) {
this.username = new SimpleStringProperty(user);
this.password = new SimpleStringProperty(pass);
this.name = new SimpleStringProperty(name);
this.surname = new SimpleStringProperty(surname);
this.email = new SimpleStringProperty(email);
this.company = new SimpleStringProperty(company);
this.phone = new SimpleStringProperty(phone);
this.canMonitorize = new SimpleBooleanProperty(monitorize);
this.canCreateProject = new SimpleBooleanProperty(createP);
this.canOpenProject = new SimpleBooleanProperty(openP);
this.admin = new SimpleBooleanProperty(admin);
}
public String getUsername() {
return username.get();
}
public void setUsername(String username) {
this.username.set(username);
}
public String getPassword() {
return password.get();
}
public void setPassword(String password) {
this.password.set(password);
}
public String getName() {
return name.get();
}
public void setName(String name) {
this.name.set(name);
}
public String getSurname() {
return surname.get();
}
public void setSurname(String surname) {
this.surname.set(surname);
}
public String getEmail() {
return email.get();
}
public void setEmail(String email) {
this.email.set(email);
}
public String getCompany() {
return company.get();
}
public void setCompany(String company) {
this.company.set(company);
}
public String getPhone() {
return phone.get();
}
public void setPhone(String phone) {
this.phone.set(phone);
}
public boolean canMonitorize() {
return canMonitorize.get();
}
public void setCanMonitorize(boolean canMonitorize) {
this.canMonitorize.set(canMonitorize);
}
public boolean canCreateProject() {
return canCreateProject.get();
}
public void setCanCreateProject(boolean canCreateProject) {
this.canCreateProject.set(canCreateProject);
}
public boolean canOpenProject() {
return canOpenProject.get();
}
public void setCanOpenProject(boolean canOpenProject) {
this.canOpenProject.set(canOpenProject);
}
public boolean isAdmin() {
return admin.get();
}
public void setAdmin(boolean isAdmin) {
this.admin.set(isAdmin);
}
}
And this is an example of the Json file:
[{"username":"admin","password":"blablabla","name":"admin","surname":"admin","email":"admin#admin.com","company":"admin","phone":"admin","admin":true}]
This is the method that should obtain the list of users:
public static List<User> getUsers(String jsonArrayStr) {
ObjectMapper mapper = new ObjectMapper();
List<User> ret;
try {
User[] userArray = mapper.readValue(jsonArrayStr, User[].class);
ret = new ArrayList<>(Arrays.asList(userArray));
} catch (IOException e) {
return new ArrayList<User>();
}
return ret;
}
The error I get when executing the code:
com.fasterxml.jackson.databind.JsonMappingException: N/A (through reference chain: object.User["username"])
When you have a public 0-args constructor it is used by default to create new POJO instance. But in your case you should not allow to create instance with default constructor because all internal fields are null and when Jackson tries to set first property, username, NullPointerException is thrown. Try to declare your constructor as below and remove default one:
#JsonCreator
public User(#JsonProperty("username") String user,
#JsonProperty("password") String pass,
#JsonProperty("name") String name,
#JsonProperty("surname") String surname,
#JsonProperty("email") String email,
#JsonProperty("company") String company,
#JsonProperty("phone") String phone,
#JsonProperty("monitorize") boolean monitorize,
#JsonProperty("createP") boolean createP,
#JsonProperty("openP") boolean openP,
#JsonProperty("admin") boolean admin) {
//your code;
}
Also, your getUsers method could look like this:
public static List<User> getUsers(String json) {
final ObjectMapper mapper = new ObjectMapper();
try {
final JavaType collectionType = mapper.getTypeFactory().constructCollectionType(List.class, User.class);
return mapper.readValue(json, collectionType);
} catch (IOException e) {
//You should not hide exceptions. Try to log it at least.
//But probably application should not start when app configuration is missing or wrong.
e.printStackTrace();
return Collections.emptyList();
}
}

Create a JSON structure from set of Java Pojo classes

I need to create a JSON object structure from set of java pojo classes. This will provide a better understand of how the objects are structured by just looking at the Json file. I tried both Gson and org.codehaus.jackson.map.ObjectMapper libraries. But couldn't generate all the Json tags relevant to all the fields in java pojo objects. The created json file is only having the values from the values stetted objects. I need to have all the fields of pojo objects in the Json file.
Gson
Hotel hotel = new Hotel(); //This hotel object includes multiple objects and those objects also include multiple objects, lists
Gson gson = new GsonBuilder().create();
String json = gson.toJson(hotel);
System.out.println(json);
ObjectMapper
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(new File("/home/Pojos.json");
This is the class and json response I got.
Hotel.java
package datatypes;
import java.util.ArrayList;
import java.util.List;
public class Hotel {
private String hotelCode;
private String chainCode;
private String hotelName;
private List<Room> rooms = new ArrayList<Room>();
private List<RoomRateRestriction> roomRateRestrictions
= new ArrayList<RoomRateRestriction>();
public String getHotelCode() {
return hotelCode;
}
public void setHotelCode(String hotelCode) {
this.hotelCode = hotelCode;
}
public String getChainCode() {
return chainCode;
}
public void setChainCode(String chainCode) {
this.chainCode = chainCode;
}
public String getHotelName() {
return hotelName;
}
public void setHotelName(String hotelName) {
this.hotelName = hotelName;
}
public List<Room> getRooms() {
return rooms;
}
public void setRooms(List<Room> rooms) {
this.rooms = rooms;
}
public void addRoom(Room room){
this.rooms.add(room);
}
public List<RoomRateRestriction> getRoomRateRestrictions() {
return roomRateRestrictions;
}
public void setRoomRateRestrictions(
List<RoomRateRestriction> roomRateRestrictions) {
this.roomRateRestrictions = roomRateRestrictions;
}
public void addRoomRateRestrictions(
RoomRateRestriction roomRateRestriction) {
this.roomRateRestrictions.add(roomRateRestriction);
}
}
JSON
{
"rooms":[],
"roomRateRestrictions":[]
}
Add serializeNulls() on GsonBuilder() to serialize null fields
Configure Gson to serialize null fields. By default, Gson omits all fields that are null
* during serialization.
class Hotel {
private String name;
private List<Guest> guests = new ArrayList<>(Collections.singleton(new Guest())); //you have to set a value in order to get the structure of the Guest class otherwise it will show an empty list []
//getter setter
}
class Guest {
private String name;
//getter setter
}
Gson
Hotel hotel = new Hotel();
Gson gson = new GsonBuilder().serializeNulls().create();
String json = gson.toJson(hotel);
System.out.println(json);
Output
{
"name":null,
"guests":[
{
"name":null
}
]
}
You can use jackson-databind library.
Maven dependency is :
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.10</version>
</dependency>
Also please find some of sample example below. Here I used Employee Object which is having nested Address object inside it.
Employee.java
public class Employee {
private int empId;
private String firstName;
private String lastName;
private double salary;
private Address address;
public Employee() {}
public Employee(int empId, String firstName, String lastName, double salary) {
this.empId = empId;
this.firstName = firstName;
this.lastName = lastName;
this.salary = salary;
}
public Employee(int empId, String firstName, String lastName, double salary, Address address) {
this.empId = empId;
this.firstName = firstName;
this.lastName = lastName;
this.salary = salary;
this.address = address;
}
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
Address.java
public class Address {
private String street;
private String city;
private String state;
private String zip;
private String country;
public Address() {}
public Address(String street, String city, String state, String zip, String country) {
this.street = street;
this.city = city;
this.state = state;
this.zip = zip;
this.country = country;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
I converted a Sample java pojo class to Json and also JSON to pojo object back.
JacksonConvertion.java
public class JacksonConvertion {
public static void main(String[] args) {
pojoToJson();
jsonToPojo();
}
private static void pojoToJson() {
try {
System.out.println("Convert Object to json ");
ObjectMapper mapper = new ObjectMapper();
Address address = new Address("#103, 1st cross, manyta tech park", "Bengaluru", "Karnataka", "560010",
"India");
Address address1 = new Address();
address1.setCity("Bengaluru");
address1.setState("Karnataka");
address1.setCountry("India");
Employee emp = new Employee(1233, "Raju", "BG", 98734.23, address1);
mapper.writeValue(new File("staff.json"), emp);
String jsonString = mapper.writeValueAsString(emp);
System.out.println(jsonString);
} catch (JsonProcessingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void jsonToPojo() {
try {
System.out.println("Convert Json to Object ");
ObjectMapper mapper = new ObjectMapper();
Employee employee = mapper.readValue(new File("staff.json"), Employee.class);
System.out.println(employee.getFirstName());
System.out.println(employee.getSalary());
System.out.println(employee.getAddress().getCity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
Also included some of links for your reference.
Link1
Link2
I think this would work fine
Add http://www.java2s.com/Code/Jar/c/Downloadcomfasterxmljacksondatabindjar.htm and http://www.java2s.com/Code/Jar/j/Downloadjacksondatabind205sourcesjar.htm to your library.
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class javaPojo {
public static void main(String args[]){
Hotel hotel = new Hotel();
ObjectMapper mapper = new ObjectMapper();
try {
String json = mapper.writeValueAsString(hotel);
System.out.println("JSON = " + json);
} catch (JsonProcessingException e) {
e.printStackTrace();
}}
}
Hotel
import java.util.ArrayList;
import java.util.List;
public class Hotel {
private String hotelCode;
private String chainCode;
private String hotelName;
private List<Room> rooms = new ArrayList<Room>();
private List<RoomRateRestriction> roomRateRestrictions
= new ArrayList<RoomRateRestriction>();
public String getHotelCode() {
return hotelCode;
}
public void setHotelCode(String hotelCode) {
this.hotelCode = hotelCode;
}
public String getChainCode() {
return chainCode;
}
public void setChainCode(String chainCode) {
this.chainCode = chainCode;
}
public String getHotelName() {
return hotelName;
}
public void setHotelName(String hotelName) {
this.hotelName = hotelName;
}
public List<Room> getRooms() {
return rooms;
}
public void setRooms(List<Room> rooms) {
this.rooms = rooms;
}
public void addRoom(Room room){
this.rooms.add(room);
}
public List<RoomRateRestriction> getRoomRateRestrictions() {
return roomRateRestrictions;
}
public void setRoomRateRestrictions(
List<RoomRateRestriction> roomRateRestrictions) {
this.roomRateRestrictions = roomRateRestrictions;
}
public void addRoomRateRestrictions(
RoomRateRestriction roomRateRestriction) {
this.roomRateRestrictions.add(roomRateRestriction);
}
}
Room
public class Room {
}
RoomRateRestriction
public class RoomRateRestriction {
}
OUTPUT - JSON = {"hotelCode":null,"chainCode":null,"hotelName":null,"rooms":[],"roomRateRestrictions":[]}

Why annotation #JsonValue does not work in Jersey?

I have RESTful service based on Jersey framework.
I need to serialize and deserialize some object which include enum fields.
I wrote two methods and annotated they with #JsonValue and #JsonCreator. But Jersey doesn't show enum fields?
My object with enum:
#XmlRootElement
public class RecipientWrapper{
#ApiModelProperty(hidden = true)
private Recipient recipient;
private String name;
private String address;
private RecipientType type;
public RecipientWrapper(){}
public RecipientWrapper(String name, String address, Message.RecipientType type) {
recipient = new Recipient(name, address, type);
}
#XmlTransient
public Recipient getRecipient(){
if (recipient == null && name != null && address != null){
if (type != null){
recipient = new Recipient(name, address, type.toMsgRecipientTypeValue());
}
else{
recipient = new Recipient(name, address, Message.RecipientType.TO);
}
}
return recipient;
}
public void setRecipient(Recipient recipient){
this.recipient = recipient;
}
public String getName(){
return recipient.getName();
}
public String getAddress(){
return recipient.getAddress();
}
public Message.RecipientType getType(){
return recipient.getType();
}
public void setName(String name) {
this.name = name;
}
public void setAddress(String address) {
this.address = address;
}
public void setType(RecipientType type) {
this.type = type;
}
public enum RecipientType {
TO,
CC,
BCC;
private static Map<String, RecipientType> nameMap = new HashMap<String, RecipientType>();
private static Map<RecipientType, Message.RecipientType> msgRecipientType = new HashMap<RecipientType, Message.RecipientType>();
static{
nameMap.put("TO", TO);
nameMap.put("CC", CC);
nameMap.put("BCC", BCC);
msgRecipientType.put(TO, Message.RecipientType.TO);
msgRecipientType.put(CC, Message.RecipientType.CC);
msgRecipientType.put(BCC, Message.RecipientType.BCC);
}
#JsonCreator
public static RecipientType forValue(String value){
return nameMap.get(StringUtils.upperCase(value));
}
#JsonValue
public String toValue(){
for (Map.Entry<String, RecipientType> entry: nameMap.entrySet()){
if (entry.getValue() == this){
return entry.getKey();
}
}
return null;
}
public Message.RecipientType toMsgRecipientTypeValue(){
for (Map.Entry<RecipientType, Message.RecipientType> entry: msgRecipientType.entrySet()){
if (entry.getKey() == this){
return entry.getValue();
}
}
return null;
}
}
}
And gradle dependencies:
compile 'javax.ws.rs:jsr311-api:1.1.1'
compile 'com.sun.jersey:jersey-server:1.18.1'
compile 'com.sun.jersey:jersey-servlet:1.18.1'
compile 'com.sun.jersey:jersey-bundle:1.18.1'
compile 'io.swagger:swagger-jersey-jaxrs:1.5.0'
compile 'org.antlr:stringtemplate:4.0.2'
compile 'org.freemarker:freemarker:2.3.22'
compile 'org.apache.velocity:velocity:1.7'
compile 'org.codemonkey.simplejavamail:simple-java-mail:2.2'
compile 'org.slf4j:slf4j-simple:1.7.12'
compile 'org.slf4j:slf4j-api:1.7.12'
compile 'org.codehaus.jackson:jackson-mapper-asl:1.9.13'
JSON Output:
{
"address": "mymail#gmail.com",
"name": "My name"
}
Why doesn't Jersey show enum fields?
The problem is the #JsonValue annotation. If you remove it - it will work.
Example:
public class A {
private String type;
private RecipientType recipientType;
public A(String type, RecipientType recipientType) {
this.type = type;
this.recipientType = recipientType;
}
public String getType() {
return type;
}
public RecipientType getRecipientType() {
return recipientType;
}
public enum RecipientType {
TO,
CC,
BCC;
}
}
When serializing it I get
{"type":"a","recipientType":"BCC"}
Jackson by itself knows to handle enums, you don't need to anything special for it. Add the #JsonValue just ruined it.

Getting null from getters method

I am getting null from getters method when trying to save it in a list and calling the list in servlet. Please help me out to get rid of this. Thanks in advance.
I am adding first the getters and setters method code then DAO code and then servlet code.
package com.vechile.model;
public class DriverSearchResult {
private String Id;
private String Name;
private String Address;
private String City;
private String Contact;
private String Country;
public String getId() {
return Id;
}
public void setId(String id) {
Id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
public String getCity() {
return City;
}
public void setCity(String city) {
City = city;
}
public String getContact() {
return Contact;
}
public void setContact(String contact) {
Contact = contact;
}
public String getCountry() {
return Country;
}
public void setCountry(String country) {
Country = country;
}
}
package com.vechile.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.vechile.model.Driver;
import com.vechile.model.DriverSearchResult;
import com.vechile.model.Searching;
import com.vechile.utils.DBConnection;
public class SearchDAO {
private String sql;
private ResultSet rs, rs1;
public boolean searchDriver(Searching searching) {
try {
sql = String.format("select * from adddriver where (%s) = '%s'",
searching.getInputList(), searching.getTxtField());
rs = DBConnection.executeQuery(sql);
if(rs.next()) {
DriverSearchResult setResult = new DriverSearchResult();
Integer id = new Integer(rs.getInt(1));
String stringID = id.toString();
setResult.setId(stringID);
setResult.setName(rs.getString(1));
setResult.setAddress(rs.getString(2));
setResult.setCity(rs.getString(3));
setResult.setContact(rs.getString(4));
setResult.setCountry(rs.getString(5));
return true;
}
} catch (Exception e) {
e.getStackTrace();
}
return false;
}
public List<DriverSearchResult> getDriverResult(){
List<DriverSearchResult> returnList = new ArrayList<DriverSearchResult>();
DriverSearchResult getResult = new DriverSearchResult();
String id = getResult.getId();
String name = getResult.getName();
String address = getResult.getAddress();
String city = getResult.getCity();
String contact = getResult.getContact();
String country = getResult.getCountry();
returnList.add(getResult);
return returnList;
}
public boolean searchBooking(Searching searching) {
try {
sql = String.format(
"select * from booking where booking_id = '%s'",
searching.getBookingSearch());
rs1 = DBConnection.executeQuery(sql);
if (rs1.next()) {
return true;
}
} catch (Exception e) {
e.getStackTrace();
}
return false;
}
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String input = request.getParameter("list");
String txtField = request.getParameter("txtField");
String op = request.getParameter("op");
String bSearch = request.getParameter("bookingSearch");
try{
if(op.equals("1")){
Searching search1 = new Searching();
search1.setInputList(input);
search1.setTxtField(txtField);
SearchDAO searchDAO = new SearchDAO();
boolean searchDriver = searchDAO.searchDriver(search1);
if(searchDriver){
DriverSearchResult searchResult = new DriverSearchResult();
System.out.println(searchResult.getId());
//response.sendRedirect("driversearchresult.jsp");
//response.sendRedirect("SearchOutPut.jsp?op=" + search1.getPassingValue());
}
else {
out.println("<html>");
out.println("<head>");
out.println("<script>");
out.println("alert('Record Not Found!')");
out.println("</script>");
out.println("<META HTTP-EQUIV= Refresh CONTENT=0;URL=SearchDriver.jsp>");
}
}
That happens because you fill DriverSearchResult object in the method searchDriver and then forget that object. Then in another method you create another instance of class DriverSearchResult and try to extract values from it without prior initialization. That's why it gives you nulls, since you never call setters on this newly created instance.
I guess you want to save DriverSearchResult instance created in searchDriver method and then use it in other methods instead of creating new one.
UPD:
I hope the idea is clear from the code snippet:
public class SearchDAO {
private List<DriverSearchResult> resultList = new ArrayList<>();
public boolean searchDriver(Searching searching) {
try {
// ...
if(rs.next()) {
DriverSearchResult setResult = new DriverSearchResult();
// ...
resultList.add(setResult); // <<<<<<<<<
return true;
}
} catch (Exception e) {
e.getStackTrace();
}
return false;
}
public List<DriverSearchResult> getDriverResult(){
return resultList; // <<<<
}
}

Assign return value to new Variable (Java)

it's been a while since I've done some java coding.
I need to build an application for a business which requires automation (part of a workshop), which is however irrelevant to my question...
I'm stuck on the line : customerList.add(customer); //(part of the addCustomer method in the WCIA class)
Also it's the first time I'm told to "Assign return value to new Variable" as part of an error, so not too sure what that means.
Code: Main
import java.util.ArrayList;
public class WCIA {
private final ArrayList customerList = null;
public static void main(String[] args) {
short s =002;
Customer arno = new Customer();
arno.setName("Arno");
arno.setId(s);
arno.setEmail("arnomeye#gmail.com");
arno.setAddress("Somewhere");
arno.setPhoneNum("0727855201");
System.out.printf("%s",arno.getEmail());
WCIA wcia = new WCIA();
wcia.addCustomer(arno);
wcia.displayCustomers();
}
public void addCustomer (Customer customer)
{
customerList.add(customer); // <---Problem over here
}
public void displayCustomers()
{
for(int x=0;x<customerList.size();x++)
{
Customer cus = (Customer) customerList.get(x);
cus.DisplayCustomer();
}
}
}
Code: Customer class:
public class Customer {
private short id;
private String name;
private String email;
private String phoneNum;
private String address;
public Customer()
{
System.out.println("Class initiated");
}
public void DisplayCustomer()
{
System.out.append("Name : "+ name+"\n");
System.out.append("ID : "+ id+"\n");
System.out.append("Email : "+ email+"\n");
System.out.append("Phone Number : "+ phoneNum+"\n");
System.out.append("address : "+ address+"\n");
}
public void setId(short id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setEmail(String email) {
this.email = email;
}
public void setPhoneNum(String phoneNum) {
this.phoneNum = phoneNum;
}
public void setAddress(String address) {
this.address = address;
}
public short getId() {
return id;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public String getPhoneNum() {
return phoneNum;
}
public String getAddress() {
return address;
}
}
You need to instantiate your ArrayList before you can assign elements to it. You're probably getting a NullPointerException, is my guess.
Change this line:
private final ArrayList customerList = null;
to
private final ArrayList customerList = new ArrayList();
Should solve at least this problem. I did not read the rest of your code so I'm not sure if other problems exist.
customerList is null and never initialized. Create an object of type ArrayList and assign it to that variable before you try to add to it.
You should declare the List with an explicit definition of the type of its elements (parametrized list):
private final List<Customer> customerList;
This way you can get rid of casting to Customer in:
Customer cus = customerList.get(x);
Finally, as good practice, initialize it in the constructor:
public WCIA()
{
customerList = new ArrayList<>();
}

Categories

Resources